Coursera Algorithms week1 Interview Questions: 3Sum in quadratic time
来源:互联网 发布:大话设计模式 php pdf 编辑:程序博客网 时间:2024/06/01 19:01
题目要求:
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;HashMapmap = new HashMap ();for(int i =0; i
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;HashMapmap = new HashMap ();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-2for (int j = i + 1; j < n; j++) {//j从i+1开始统计,不会超过n-1int smallValue = a[i] + a[j]; //因为排好序了,所以最开始的a[i]+a[j]if (smallValue > target) //当a[i]+a[j]>target时没必要计算了,因为后续的查找就会重复break;int bigValue = target-smallValue; //计算出对应的数值较大的valueInteger 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));}}
阅读全文
0 0
- Coursera Algorithms week1 Interview Questions: 3Sum in quadratic time
- Coursera Algorithms week1 Interview Questions: Search in a bitonic array
- Coursera Algorithms week1 Interview Questions: Egg drop
- Coursera Algorithms week1 练习测验3:Successor with delete
- Coursera Algorithms week1 练习测验1:Social network connectivity
- top interview questions 3
- Sum up - Linux Interview Questions (Updating)
- Sum up - Java Thread Interview Questions (Updating)
- Frequently Asked Questions in English Interview
- Some common questions in English Interview
- 3-Collections Framework Interview Questions
- 20161124 Coursera Stanford-MachineLearning/Week1-3
- 算法设计Week1 LeetCode Algorithms Problem #1 Two Sum
- First time interview in Toronto
- Interview Questions
- interview questions
- Interview Questions
- interview questions
- HTML基础和JSP了解及JSP中代码加载顺序
- intelliJ Idea自带热部署和Jrebel实现热部署
- Joda-Time的使用
- 一个经典例子让你彻彻底底理解java回调机制
- Java中的ReentrantLock和synchronized两种锁定机制的对比
- Coursera Algorithms week1 Interview Questions: 3Sum in quadratic time
- opensips 服务器搭建测试
- mysql数据库连接池dbcp与c3p0对比
- SQL语句执行顺序
- Centos下安装yaf扩展
- jQuery注册表格(table)行(tr)点击选中checkbox事件
- STL的priority_queue及其背后的heap读书笔记
- HttpRequestUtil
- C++ 引用的作用和用法