We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
位置:哈希表-四数之和-Java版本答案 修改1:
for (int k = 0; k < nums.length; k++) {
for (int i = k + 1; i < nums.length; i++) {
for (int k = 0; k < nums.length - 3; k++) {
for (int i = k + 1; i < nums.length - 2; i++) {
修改2:删除了原答案的测试代码,即
public static void main(String[] args) { Solution solution = new Solution(); int[] nums = {1, 0, -1, 0, -2, 2}; int target = 0; List<List<Integer>> results = solution.fourSum(nums, target); for (List<Integer> result : results) { System.out.println(result); } }
修改后正确的版本:
import java.util.*; public class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { Arrays.sort(nums); // 排序数组 List<List<Integer>> result = new ArrayList<>(); // 结果集 for (int k = 0; k < nums.length - 3; k++) { // 剪枝处理 if (nums[k] > target && nums[k] >= 0) { break; // 此处的break可以等价于return result; } // 对nums[k]去重 if (k > 0 && nums[k] == nums[k - 1]) { continue; } for (int i = k + 1; i < nums.length - 2; i++) { // 第二级剪枝 if (nums[k] + nums[i] > target && nums[k] + nums[i] >= 0) { break; // 注意是break到上一级for循环,如果直接return result;会有遗漏 } // 对nums[i]去重 if (i > k + 1 && nums[i] == nums[i - 1]) { continue; } int left = i + 1; int right = nums.length - 1; while (right > left) { long sum = (long) nums[k] + nums[i] + nums[left] + nums[right]; if (sum > target) { right--; } else if (sum < target) { left++; } else { result.add(Arrays.asList(nums[k], nums[i], nums[left], nums[right])); // 对nums[left]和nums[right]去重 while (right > left && nums[right] == nums[right - 1]) right--; while (right > left && nums[left] == nums[left + 1]) left++; right--; left++; } } } } return result; } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
位置:哈希表-四数之和-Java版本答案
修改1:
修改2:删除了原答案的测试代码,即
修改后正确的版本:
The text was updated successfully, but these errors were encountered: