标签:0015 nums 3Sum res 复杂度 high while low LeetCode
1. 题目描述
2. Solution 1
1、思路分析
3重循环,实现略
3. Solution 2
1、思路分析
固定一个数,另外两个数用双指针定位。
2、代码实现
package Q0099.Q0015ThreeSum;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/*
方法一: 暴力解法
三重循环, time: O(n^3), space: O(1)
*/
public class Solution {
/*
方法二: 固定一个数,另两个数用双指针
time: O(n^2)
*/
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
// corner case
if (nums == null || nums.length < 3) return res;
// sort array
Arrays.sort(nums);
// for loop to locate the first num
for (int i = 0; i < nums.length - 2; i++) {
// skip duplicates
if (i > 0 && nums[i] == nums[i - 1]) continue;
int low = i + 1, high = nums.length - 1;
// two pointer in while loop
while (low < high) {
if (nums[low] + nums[high] == -nums[i]) {
res.add(Arrays.asList(nums[i], nums[low], nums[high]));
// move two pointers, don't forget check duplicates
while (low < high && nums[low] == nums[low + 1]) low++;
while (low < high && nums[high] == nums[high - 1]) high--;
low++;
high--;
} else if (nums[low] + nums[high] < -nums[i]) low++; // small
else high--; // large
}
}
return res;
}
}
3、复杂度分析
时间复杂度: O(n ^ 2)
空间复杂度: O(log n)。忽略存储答案的空间,额外的排序的空间复杂度为O(log n)。
标签:0015,nums,3Sum,res,复杂度,high,while,low,LeetCode 来源: https://www.cnblogs.com/junstat/p/15962758.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。