标签:四数 temp nums int 三数 high add low Leetcode
Leetcode 三数之和、四数之和
三数之和
// 暴力会超时,这里采用排序 + 双指针
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
if(i > 0 && nums[i] == nums[i - 1]) continue;
int oppositeNum = -nums[i];
int j = i + 1, k = nums.length - 1;
while(j < k){
if(nums[j] + nums[k] > oppositeNum){
k--;
}else if(nums[j] + nums[k] < oppositeNum){
j++;
}else{
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
res.add(temp);
while(j < k && nums[j] == nums[j + 1]) j++;
while(j < k && nums[k] == nums[k - 1]) k--;
j++;
k--;
}
}
}
return res;
}
}
四数之和
// 与三数之和类似,注意删除重复元素
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; i++){
for(int j = nums.length - 1; j >= 0; j--){
while(j != nums.length - 1 && j != 0 && nums[j] == nums[j + 1]) j--;
while(i != nums.length - 1 && i != 0 && nums[i] == nums[i - 1]) i++;
int low = i + 1, high = j - 1;
while(low < high){
if(nums[i] + nums[j] + nums[low] + nums[high] < target){
low++;
}else if(nums[i] + nums[j] + nums[low] + nums[high] > target){
high--;
}else{
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[low]);
temp.add(nums[high]);
temp.add(nums[j]);
res.add(temp);
low++;
high--;
while(low < high && nums[high] == nums[high + 1]) high--;
while(low < high && nums[low] == nums[low - 1]) low++;
}
}
}
}
return res;
}
}
标签:四数,temp,nums,int,三数,high,add,low,Leetcode 来源: https://blog.csdn.net/Aetherzzz/article/details/115003978
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。