题目要求:

Design an algorithm for the 3-SUM problem that takes time proportional to n2 in the worst case. You may assume that you can sort the n integers in time proportional to n2 or better.

分析:

《算法4》这本书提供的TwoSumFast解法为NlogN,ThreeSumFast解法为N2logN,根据课后练习,要实现3Sum复杂度为N2,建议先把2Sum复杂度实现为N。同时教材提示用排好序的数组可以实现复杂度N。我想了很久,没有发现排好序的数组对复杂度降至N有太大帮助,于是在网上搜索了下大家的做法。网上的大部分都是建议用set或map来做,我决定采用map试试,果然用map很方便。代码如下:

 import java.util.Arrays;
import java.util.HashMap; public class TwoSumLinear {
public static int count(int[] a){
int cnt = 0;
int n = a.length;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i =0; i<n;i++){
if(map.get(a[i]) == null) map.put(a[i], i);
Integer negIndex = map.get(-a[i]);
if(negIndex != null && negIndex != i){
System.out.println("a["+negIndex+"]="+(-a[i])+"和a["+i+"]="+a[i]);
cnt++;
}
}
return cnt;
}
public static void main(String[] args){
int[] a = { 30, -40, -20, -10, 40, 0, 10, 5 };
System.out.println(Arrays.toString(a));
System.out.println(count(a));
}
}

3Sum的作业提示可以先将数组排序,基于这个思路,结合写过的2Sum线性实现方法,写出了复杂度为N2的3Sum,个人认为实现的方式已经很精简了。

 import java.util.Arrays;
import java.util.HashMap; public class ThreeSumQuadratic {
public static int count(int[] a, int target) {
Arrays.sort(a);// 数组从小到大排序,后面要使用有序数组的性质简化运算
System.out.println(Arrays.toString(a));
System.out.println("target="+target);
int cnt = 0;
int n = a.length;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
map.put(a[i], i); //以数组value为key,index为map值
}
for (int i = 0; i < n - 1; i++) {//i不会超过n-2
for (int j = i + 1; j < n; j++) {//j从i+1开始统计,不会超过n-1
int smallValue = a[i] + a[j]; //因为排好序了,所以最开始的a[i]+a[j]
if (smallValue > target) //当a[i]+a[j]>target时没必要计算了,因为后续的查找就会重复
break;
int bigValue = target-smallValue; //计算出对应的数值较大的value
Integer bigIndex = map.get(bigValue); //查找数值较大的value所在的位置
if (bigIndex != null && bigIndex > i && bigIndex > j) {
System.out.println(
"[" + i + "]=" + a[i] + ",[" + j + "]" + a[j] + ",[" + bigIndex + "]" + (bigValue));
cnt++;
}
}
}
return cnt;
} public static void main(String[] args) {
int[] a = { 30, -40, -20, -10, 40, 0, 10, 5 };
System.out.println(count(a,0));
}
}

Coursera Algorithms week1 算法分析 练习测验: 3Sum in quadratic time的更多相关文章

  1. Coursera Algorithms week1 算法分析 练习测验: Egg drop 扔鸡蛋问题

    题目原文: Suppose that you have an n-story building (with floors 1 through n) and plenty of eggs. An egg ...

  2. Coursera Algorithms week1 查并集 练习测验:3 Successor with delete

    题目原文: Given a set of n integers S = {0,1,…,N-1}and a sequence of requests of the following form: Rem ...

  3. Coursera Algorithms week1 查并集 练习测验:2 Union-find with specific canonical element

    题目原文: Add a method find() to the union-find data type so that find(i) returns the largest element in ...

  4. Coursera Algorithms week1 查并集 练习测验:1 Social network connectivity

    题目原文描述: Given a social network containing. n members and a log file containing m timestamps at which ...

  5. Coursera Algorithms week3 快速排序 练习测验: Decimal dominants(寻找出现次数大于n/10的元素)

    题目原文: Decimal dominants. Given an array with n keys, design an algorithm to find all values that occ ...

  6. Coursera Algorithms week3 快速排序 练习测验: Selection in two sorted arrays(从两个有序数组中寻找第K大元素)

    题目原文 Selection in two sorted arrays. Given two sorted arrays a[] and b[], of sizes n1 and n2, respec ...

  7. Coursera Algorithms week3 快速排序 练习测验: Nuts and bolts

    题目原文: Nuts and bolts. A disorganized carpenter has a mixed pile of n nuts and n bolts. The goal is t ...

  8. Coursera Algorithms week3 归并排序 练习测验: Shuffling a linked list

    题目原文: Shuffling a linked list. Given a singly-linked list containing n items, rearrange the items un ...

  9. Coursera Algorithms week3 归并排序 练习测验: Counting inversions

    题目原文: An inversion in an array a[] is a pair of entries a[i] and a[j] such that i<j but a[i]>a ...

随机推荐

  1. MyEclipse快捷键 (精简)

    在调试程序的时候,我们经常需要注释一些代码,在用Myeclipse编程时,就可以用 Ctrl+/ 为选中的一段代码加上以 // 打头的注释:当需要恢复代码功能的时候,又可以用Ctrl+/ 去掉注释.这 ...

  2. CSS动画:旋转卡片效果

    <!DOCTYPE html> <html> <head> <title>demo</title> </head> <bo ...

  3. servlet学习总结(一)——HttpServletRequest(转载)

    原文地址:http://www.cnblogs.com/xdp-gacl/p/3798347.html 一.HttpServletRequest介绍 HttpServletRequest对象代表客户端 ...

  4. Django中 基于form的注册,基于ajax的登录

    1 form.py中写register的的form组件 from django import forms class Register(forms.Form): # 注册的form username ...

  5. iptables详解(5):iptables匹配条件总结之二(常用扩展模块)

    所属分类:IPtables  Linux基础 在本博客中,从理论到实践,系统的介绍了iptables,如果你想要从头开始了解iptables,可以查看iptables文章列表,直达链接如下 iptab ...

  6. php第十四节课

    投票 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.o ...

  7. RESTful API 学习【第1篇】

    一. 什么是RESTful REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移” REST从资源的角 ...

  8. 使用Robo 3T 软件管理MongoDB数据库如何执行命令行shell

    比如使用命令行的方式查看数据库runoobdb中的sites集合(数据表)中的所有数据 1.在连接名的地方鼠标右键选择“open shell” 2.在出现的shell窗口中输入一下命令行,然后按ctr ...

  9. SSH远程执行命令环境变量问题

    SSH命令格式 usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec] [-D [bind_address: ...

  10. Shell脚本备份数据库

    使用crontab 定时备份数据库 1. 编辑crontab 规则,定时执行脚本 2. 在my.cnf 文件中加 [mysqldump] user=root password=密码 3.编写shell ...