NSUM问题
1、两数之和
力扣第1题,两数之和
[1]两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
// 无序就使用hash表
// key:元素 value:元素的位置
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i];
// 加入元素到hashMap前先判断
if (map.containsKey(temp)) {
return new int[]{map.get(temp), i};
}
map.put(nums[i], i);
}
return new int[]{-1, -1};
}
}
2、三数之和
力扣第15题,三数之和
[15]三数之和
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new LinkedList<>();
// 先将数组从小到大排序
Arrays.sort(nums);
// 每次选好
for (int i = 0; i < nums.length - 2; i++) {
// 条件判断
if (nums[i] > 0) {
return result;
}
// 防止重复的元素加入到结果集
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
// 去重
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
left++;
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
right--;
} else if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
}
}
}
return result;
}
}
3、两数之和Ⅱ-输入有序数组
力扣第167题,两数之和Ⅱ-输入有序数组
[167]两数之和 II-输入有序数组
class Solution {
public int[] twoSum(int[] numbers, int target) {
// 遇见排序就使用左右指针
for (int left = 0; left < numbers.length - 1; left++) {
// 跳过重复元素
if (left > 0 && numbers[left] == numbers[left - 1]) {
continue;
}
int right = numbers.length - 1;
while (left < right) {
// 结果比较
int sum = numbers[left] + numbers[right];
if (sum == target) {
return new int[]{left + 1, right + 1};
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
// 找不到
return new int[]{-1, -1};
}
}
4、四数之和
力扣第18题,四数之和
[18]四数之和
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new LinkedList<>();
// 先将数组进行排序
Arrays.sort(nums);
// 排序后就可以用指针开始遍历
for (int i = 0; i < nums.length - 3; i++) {
// 去重
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length - 2; j++) {
// 去重
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int left = j + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
// 去重
while (left < right && nums[left] == nums[++left]) ;
while (left < right && nums[right] == nums[--right]) ;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return result;
}
}
文章介绍了LeetCode中与数组求和相关的经典问题,包括两数之和、三数之和、两数之和II(输入有序数组)以及四数之和的解决方案。主要使用了排序、哈希表和双指针等算法思想来解决这些问题。
&spm=1001.2101.3001.5002&articleId=128596917&d=1&t=3&u=a1479ed2b2d24d1e94a13c54379281e6)
742

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



