题目要求:

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. 关于Qt 报QDomDocument: No such file or directory错误解决办法

    肯定是没有找到相关的路径,这时候只需要在.pro文件中加入便好了,比如我要用到读写xml的一些头文件,则需要在.pro中加入如下代码: 就可以正常引用了.

  2. Makefile精髓篇【转】

    什么是makefile?或许非常多Winodws的程序猿都不知道这个东西,由于那些Windows的IDE都为你做了这个工作,但我觉得要作一个好的和professional的程序猿,makefile还是 ...

  3. PHP采用301跳转方式防CC拦截

    PHP采用301跳转方式防CC拦截   降低CC攻击的效果 <?php empty($_SERVER['HTTP_VIA']) or exit('Access Denied'); $second ...

  4. CAD绘制一个线型标注(com接口VB语言)

    主要用到函数说明: _DMxDrawX::DrawDimRotated 绘制一个线型标注.详细说明如下: 参数 说明 DOUBLE dExtLine1PointX 输入第一条界线的起始点X值 DOUB ...

  5. PAT_A1066#Root of AVL Tree

    Source: PAT A1066 Root of AVL Tree (25 分) Description: An AVL tree is a self-balancing binary search ...

  6. JS布尔值(Boolean)转换规则

    原文作者: louis 原文链接: http://louiszhai.github.io/2015/12/11/js.boolean/ 语法 众所周知, JavaScript有五个基本的值类型:num ...

  7. PAT 1104 Sum of Number Segments

    Given a sequence of positive numbers, a segment is defined to be a consecutive subsequence. For exam ...

  8. 《Java JDK 8 学习笔记》序

    摘录自<Java JDK 8 学习笔记> 翻开一本书,无非是想从书中得到知识,只是为何你要得到书中的知识,才是我想知道的答案,而这个答案决定了你在取得知识的过程中是否快乐! 多数人在取得知 ...

  9. vue 底部bottomnav

    <template> <div id="foot"> <div class="tabBar"> <div class= ...

  10. 【Codeforces 63C】Bulls and Cows

    [链接] 我是链接,点我呀:) [题意] 给你一个长度为4的数字序列(每个数字都在0~9之间,且不重复出现) 现在让你猜这个长度为4的序列是什么. 猜了之后对方会告诉有几个数字是位置和数字都正确的(猜 ...