如何在Java中实现3Sum?

时间:2016-11-19 06:32:52

标签: java algorithm sum

我想实现一个3Sum并且遇到了以下实现,为什么它为0 - num[i]求和?

假设第一个索引在数组num中有一个整数5,不是-5那么num[lo] + num[hi]== sum总是为正public List<List<Integer>> threeSum(int[] num) { Arrays.sort(num); List<List<Integer>> res = new LinkedList<>(); for (int i = 0; i < num.length-2; i++) { if (i == 0 || (i > 0 && num[i] != num[i-1])) { int lo = i+1, hi = num.length-1, sum = 0 - num[i]; while (lo < hi) { if (num[lo] + num[hi] == sum) { res.add(Arrays.asList(num[i], num[lo], num[hi])); while (lo < hi && num[lo] == num[lo+1]) lo++; while (lo < hi && num[hi] == num[hi-1]) hi--; lo++; hi--; } else if (num[lo] + num[hi] < sum) lo++; else hi--; } } } return res; } 时这是否定的?

谢谢

  function checkElementToBeInView(elem, callback) {
  $(elem).each(function() {
    var element = $(this);
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = element.offset().top;
    var elemBottom = elemTop + element.height();
    var isInView = ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    callback(element, isInView);
  });
}
$(window).on("load resize scroll", function(e) {
  checkElementToBeInView(".box", function(elem, isInView) {
    if (isInView)
      elem.addClass('active');
    else
      elem.removeClass('active');
  });

1 个答案:

答案 0 :(得分:1)

我们应该找到这样的ABC -

A + B + C = 0

可以写成 -

B + C = 0 - A

您尝试查找num[lo]num[hi]以及num[i]总和为0.您已选择num[i],所以您需要确保其他两个总和达-num[i]

num[i] + (num[lo] + num[hi])
=> num[i] + (-num[i])
=> 0