1. Two Sum
这个不用多说,两个for-loop搞定。
public class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums.length <= 1) {
return null;
}
for (int i = 0; i < nums.length; i ++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
int[] output = {i, j};
return output;
}
}
}
return null;
}
}
11. Container With Most Water
本来用两个for-loop做结果超时了。后来发现可以用一个循环的。从循环分别从两边出发,哪个小就往下移动一位。
public class Solution {
public int maxArea(int[] height) {
int max = 0;
int left = 0;
int right = height.length - 1;
while (left < right && left >= 0 && right <= height.length - 1) {
max = Math.max(max, Math.min(height[left], height[right]) * (right - left));
if (height[left] > height[right]) {
right--;
}
else {
left++;
}
}
return max;
}
}
15. 3Sum
这道题先排序,然后用一个for-loop进行循环,循环中一个node往右移动,其他两个用一个while-loop从两边向中间移动。
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
int len=nums.length;
if(len<3)
return res;
// sort array before use
Arrays.sort(nums);
for(int i=0;i<len;i++){
// when all node larger then 0
if(nums[i]>0)break;
// overlook some repiete number
if(i>0 && nums[i]==nums[i-1])continue;
int begin=i+1,end=len-1;
while(begin<end){
int sum=nums[i]+nums[begin]+nums[end];
if(sum==0){
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);list.add(nums[begin]);list.add(nums[end]);
res.add(list);
begin++;end--;
// jump repeat number
while(begin<end && nums[begin]==nums[begin-1])begin++;
while(begin<end && nums[end]==nums[end+1])end--;
}else if(sum>0)end--;
else begin++;
}
}
return res;
}
}
16. 3Sum Closest
这道题思路和15. 3Sum的差不多。。。
public class Solution {
public int threeSumClosest(int[] nums, int target) {
if (nums.length < 3) {
return target;
}
Arrays.sort(nums);
int output = nums[0] + nums[1] + nums[2];
int closest = Math.abs(target - output);
for (int i = 0; i < nums.length; i++) {
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
int diff = Math.abs(sum - target);
if (diff < closest) {
closest = diff;
output = sum;
}
if (sum > target) {
right--;
}
else if (sum < target) {
left++;
}
else {
return output;
}
}
}
return output;
}
}