public class Solution {
/**
* @param nums: an array of integer
* @param target: an integer
* @return: an integer
*/
public int twoSum2(int[] nums, int target) {
// Write your code here
if(nums == null || nums.length == 0) return 0;
Arrays.sort(nums);
int count = 0;
int left = 0;
int right = nums.length - 1;
while(left < right){
if(nums[left] + nums[right] <= target){
left ++;
} else {
count += right - left;
right --;
}
}
return count;
}
}
总的思路对了,但是一开始的做法掉到了坑里,就是用 i = 1 to n 做最外循环,j 和 k 都在 i 后面。
所以顺着这个问题想,如果我们最外围遍历的是 k,而 i, j 都处于 k 的左面,那么每次就只有一个正确方向,挪动一个指针可以保证正确性了,即让 num[i] + num[j] 变大,或者变小。
public class Solution {
/**
* @param S: A list of integers
* @return: An integer
*/
public int triangleCount(int S[]) {
// write your code here
Arrays.sort(S);
int count = 0;
for(int k = 0; k < S.length; k++){
int i = 0;
int j = k - 1;
while(i < j){
if(S[i] + S[j] <= S[k]){
i ++;
} else {
count += j - i;
j --;
}
}
}
return count;
}
}
public class Solution {
/**
* @param heights: an array of integers
* @return: an integer
*/
public int maxArea(int[] heights) {
// write your code here
if(heights == null || heights.length == 0) return 0;
int max = 0;
int left = 0;
int right = heights.length - 1;
while(left < right){
int width = right - left;
int curArea = Math.min(heights[left], heights[right]) * width;
max = Math.max(max, curArea);
if(heights[left] < heights[right]){
left ++;
} else {
right --;
}
}
return max;
}
}