Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Algorithms Analysis #4

Open
barretlee opened this issue May 24, 2016 · 0 comments
Open

Algorithms Analysis #4

barretlee opened this issue May 24, 2016 · 0 comments

Comments

@barretlee
Copy link
Owner

从一堆顺序排列的整数中任选三个,其和为 0 则为一组,类似这样的组有多少?

分析方法:任选两个组合为 0,得出一个暴力算法:twoSum.js,类比可以得到 threeSum.js

两个算法的时间复杂度都是很高的,结合 #1 提到的二分法降低复杂度,得到:twoSumFast.jsthreeSumFast.js

代码地址:/chapters/chapter-1-fundamentals/1.4-analysis-of-algorithms/threeSumFast.js

function threeSumFast(input) {
  var counter = 0;
  for(var i = 0, len = input.length; i < len - 2; i++) {
    for(var j = i; j < len - 1; j++) {
      var searchKey = -1 * (input[i] + input[j]);
      if(rank(input, searchKey) > -1) {
        counter++;
      }
    }
  }
  return counter;

  function rank(a, k){
    var start = 0;
    var end = a.length - 1;
    while(start <= end) {
      var mid = Math.floor((end - start) / 2) + start;
      if(k < a[mid]) {
        end = mid - 1;
      } else if(k > a[mid]) {
        start = mid + 1;
      } else {
        return mid;
      }
    }
    return -1;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant