LeetCode力扣15.三數之和

題目描述:

給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組。

注意:答案中不可以包含重複的三元組。

例如, 給定數組 nums = [-1, 0, 1, 2, -1, -4],

滿足要求的三元組集合爲:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

例如, 給定數組 nums = [0, 0, 0, 0, -1, 0],

滿足要求的三元組集合爲:
[
  [0, 0, 0]
]

 解題思路:

一、暴力法:先排個序,去除重複的元素、暴力循環找出三數和相加等於0的數放進List,再去重數組,時間複雜度O(n^3)

二、巧妙:先排個序,去除重複的元素、模擬雙指針,時間複雜度O(n^2)

代碼:

一、暴力法:時間複雜度O(n^3) 。注:與通過的實例對比沒錯誤,but 311 / 313 個通過測試用例(第311個用例沒通過原因:超出時間限制)

public static List<List<Integer>> threeSum(int[] nums) {
		Arrays.sort(nums);
		List<List<Integer>> ls = new ArrayList<>();
		for (int i = 0; i < nums.length - 2; i++) {
			if (i > 0 && nums[i - 1] == nums[i])
				continue; // 去重
			for (int j = i + 1; j < nums.length - 1; j++) 
				for (int k = j + 1; k < nums.length; k++) 
					if (nums[k] + nums[i] + nums[j] == 0)
						ls.add(Arrays.asList(nums[i], nums[j], nums[k]));
		}
		Set<List<Integer>> middleLinkedHashSet = new LinkedHashSet<>(ls);
		List<List<Integer>> afterHashSetList = new ArrayList<>(middleLinkedHashSet);
		return afterHashSetList;
	}

二、排序+雙指針:時間複雜度O(n^2)

public List<List<Integer>> threeSum2(int[] nums) {
		Arrays.sort(nums); // 排序
		List<List<Integer>> tuples = new ArrayList<>();
		for (int i = 0; i < nums.length - 2; i++) {
			if (i > 0 && nums[i - 1] == nums[i]) continue; // 去重
			
			int first = i + 1, last = nums.length - 1;
			while (first < last) { // 因爲如果只 first++ last 不變的話,即使得到了結果也是重複的
				if (nums[last] > -nums[i] - nums[first]) {
					while (first < last && nums[last - 1] == nums[last])
						last--; // 右指針去重
					last--;
				} else if (nums[last] < -nums[i] - nums[first]) {
					while (first < last && nums[first + 1] == nums[first])
						first++; // 左指針去重
					first++;
				} else {
					tuples.add(Arrays.asList(nums[i], nums[first], nums[last]));
					while (first < last && nums[last - 1] == nums[last])
						last--; // 左指針去重
					while (first < last && nums[first + 1] == nums[first])
						first++; // 右指針去重
					last--;
					first++;
				}
			}
		}
		return tuples;
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章