Coursera Algorithms week1 算法分析 练习测验: 3Sum in quadratic time
题目要求:
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的更多相关文章
- Coursera Algorithms week1 算法分析 练习测验: Egg drop 扔鸡蛋问题
题目原文: Suppose that you have an n-story building (with floors 1 through n) and plenty of eggs. An egg ...
- 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 ...
- 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 ...
- Coursera Algorithms week1 查并集 练习测验:1 Social network connectivity
题目原文描述: Given a social network containing. n members and a log file containing m timestamps at which ...
- Coursera Algorithms week3 快速排序 练习测验: Decimal dominants(寻找出现次数大于n/10的元素)
题目原文: Decimal dominants. Given an array with n keys, design an algorithm to find all values that occ ...
- 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 ...
- 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 ...
- Coursera Algorithms week3 归并排序 练习测验: Shuffling a linked list
题目原文: Shuffling a linked list. Given a singly-linked list containing n items, rearrange the items un ...
- 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 ...
随机推荐
- SetACL 使用方法详细参数中文解析
示例: SetACL.exe c:\nihao /dir /deny everyone /read_ex 设置E:\wxDesktop 文件夹 everyone 用户为读取和运行权限 SetACL M ...
- Centos 安装 Moosefs文件系统
一.环境介绍Moosefs master:192.168.55.148Moosefs Metalogger:192.168.55.149Moosefs Chunk-01:192.168.55.150M ...
- POJ_3013_最短路
Big Christmas Tree Time Limit: 3000MS Memory Limit: 131072K Total Submissions: 23630 Accepted: 5 ...
- UICollectionView(一)基本概念
整体预览 高等级的包含和管理(Top-level containment and management) UICollectionView UICollectionViewController UIC ...
- LIS(两种方法求最长上升子序列)
首先得明白一个概念:子序列不一定是连续的,可以是断开的. 有两种写法: 一.动态规划写法 复杂度:O(n^2) 代码: #include <iostream> #include <q ...
- PostgreSQL使用总结
最近项目用到了PostgreSQL数据库,网上一堆教程,这里自己整理一下做个笔记: 1,下载安装,我这边安装在Windows7,在这里找到大象一样的标志: 2,双击打开,这里的话按流程直接走: 3,这 ...
- Linux - docker基础
目录 Linux - docker基础 docker的概念 docker安装流程 docker基本命令学习 docker 的 hello docker 运行一个ubuntu容器 Docker与Cent ...
- SqlServer转换为Mysql(mss2sql)
SqlServer转换为Mysql(mss2sql)工具 http://pan.baidu.com/s/1c2d8R8O 参考链接: http://www.cnblogs.com/angestudy/ ...
- noip模拟赛 计数
[问题描述] 给出m个数a[1],a[2],…,a[m] 求1~n中有多少数不是a[1],a[2],…,a[m]的倍数. [输入] 输入文件名为count.in. 第一行,包含两个整数:n,m 第二行 ...
- [bzoj1468][poj1741]Tree_点分治
Tree bzoj-1468 poj-1741 题目大意:给你一颗n个点的树,求树上所有路径边权和不大于m的路径条数. 注释:$1\le n\le 4\cdot 10^4$,$1\le m \le 1 ...