提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
一、力扣1. 两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i ++){
map.put(nums[i], i);
}
int[] res = new int[2];
for(int i = 0; i < nums.length ; i ++){
int cur = target - nums[i];
if(map.containsKey(cur)){
if(map.get(cur) != i){
res[0] = i;
res[1] = map.get(cur);
break;
}
}
}
return res;
}
}
二、力扣15. 三数之和
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
if(nums[0] > 0)return res;
for(int i = 0; i < nums.length-2; i ++){
int left = i+1, right = nums.length-1;
int cur = -nums[i];
for(;left < right;){
int sum = nums[left] +nums[right];
if(sum > cur){
right --;
}else if(sum < cur){
left ++;
}else{
List<Integer> li = new ArrayList<>();
li.add(nums[i]);
li.add(nums[left]);
li.add(nums[right]);
res.add(li);
while(left < right && nums[left] == nums[left+1])left++;
while(left < right && nums[right] == nums[right-1])right--;
left ++;
right --;
}
}
while(i < nums.length -2 && nums[i] == nums[i+1])i ++;
}
return res;
}
}
三、力扣18. 四数之和
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length - 3; i ++){
if(target < 0 && nums[i] > 0)return res;
for(int j = i + 1; j < nums.length - 2; j ++){
for(int left = j + 1, right = nums.length-1; left < right;){
int cur = nums[left] + nums[right] + nums[i] + nums[j];
if(cur > target){
right --;
}else if(cur < target){
left ++;
}else{
List<Integer> li = new ArrayList<>();
li.add(nums[i]);
li.add(nums[j]);
li.add(nums[left]);
li.add(nums[right]);
res.add(li);
while(left < right && nums[left] == nums[left+1])left++;
while(left < right && nums[right] == nums[right-1])right--;
left ++;
right --;
}
}
while(j < nums.length-2 && nums[j] == nums[j+1])j ++;
}
while(i < nums.length-1 && nums[i] == nums[i+1])i ++;
}
return res;
}
}
本文详细介绍了力扣平台上三个经典问题的Java解决方案:两数之和、三数之和和四数之和,分别涉及哈希映射、数组操作和排序技巧。

被折叠的 条评论
为什么被折叠?



