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 ...
随机推荐
- demo记录
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http ...
- WING IDE 快捷键
工欲善其事必先利其器,所以我们无论使用什么编译器,都要熟悉一些快捷键. Ctrl+N新建文件 Ctrl+O 打开文件夹 Ctrl+W 关闭当前文件 Ctrl+S 保存文件 Ctrl+shif+S 另存 ...
- adjtimex和时钟的几个概念tick,freq,ppm,jiffies
adjtimex使用 今天遇到一个ntp的同步问题.服务器上配置好了ntpd,在启动前也手动进行过同步,但是过段时间ntpq查询发现服务器即便能选出同步服务器,但是系统的时间偏差越来越大. 服务器上实 ...
- Netty 长连接服务
转自:https://www.dozer.cc/2014/12/netty-long-connection.html 推送服务 还记得一年半前,做的一个项目需要用到 Android 推送服务.和 iO ...
- 51nod1006 -最长公共子序列Lcs【动态规划】
给出两个字符串A B,求A与B的最长公共子序列(子序列不要求是连续的). 比如两个串为: abcicba abdkscab ab是两个串的子序列,abc也是,abca也是,其中abca是这两个字符串最 ...
- git连接github mac
话不多说,终端里的代码直接复制过来 Last login: Fri May 17 21:45:31 on ttys000 liuduoduodeMacBook-Air:~ liuxiangyang$ ...
- css图片居中(水平居中和垂直居中)
css图片居中(水平居中和垂直居中) css图片居中分css图片水平居中和垂直居中两种情况,有时候还需要图片同时水平垂直居中,下面分几种居中情况分别介绍. css图片水平居中 利用margin: 0 ...
- 腾讯云&搭建微信小程序服务
准备域名和证书 任务时间:20min ~ 40min 小程序后台服务需要通过 HTTPS 访问,在实验开始之前,我们要准备域名和 SSL 证书. 域名注册 如果您还没有域名,可以在腾讯云上选购,过程可 ...
- Huawei-R&S-网络工程师实验笔记20190608-VLAN划分基础(基于端口、MAC地址、子网地址、协议)
>Huawei-R&S-网络工程师实验笔记20190608-VLAN划分基础(基于端口.MAC地址.子网地址.协议) >>实验开始,先上拓扑图参考: 一.基于端口划分VLAN ...
- IDEA 工具使用报错总结
读前语:此文章仅给非入门级观看 1.使用Debug 无法运行,而使用Run 则正常启动,报错代码如下 1 Error running 'jx_web': Unable to open debugge ...