我想实现一个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');
});
答案 0 :(得分:1)
我们应该找到这样的A
,B
和C
-
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