3Sum - Learning Notes

3Sum - Learning Notes

topic

Leetcode above 3Sum problem .
Looking from a given array of three numbers, such that the number of three and equal to the target value (target)

Thinking

First, we can put the problem into 2Sum 3Sum problem . For each number in the array num, we just need to find the other two numbers, so that the two numbers is equal to (target - num).

Such an approach will have a small problem, at this time if there are the same number of two or more, then the number will get the same result, this way every time we would judge must first obtain a solution is not the same. To address this issue, we first sort the array , the same number are concentrated into one.

There is a very simple method for sorting an array of good demand 2Sum, for example:

Array: [1,3,5,6,7,9]
target:. 11

First find the minimum 1, maximum 9. Adding up to 10, less than 11, the minimum value at this time can not find a higher value such that it satisfies (1 + num = 11), so deleting 1.

Array: [3,5,6,7,9]
target:. 11

3 continues to find the minimum, maximum, sum of two 9 12, greater than 11, the maximum value can not be found at this time to satisfy a smaller value (9 + num = 11), 9 omitted.

Array: [3,5,6,7]
target:. 11

Repeat until the two values ​​are found equal to 11.

Code

void Fun(int *nums, int length, int target) {
	if (nums == NULL || length < 3)
		return;

	// 排序
	sort(nums, nums + length);

	//对每个值进行寻找,将3Sum 转化为2Sum问题
	for (int i = length - 1; i > 1;) {
		int min = 0;
		int max = i - 1;

		while (min < max) {
			int num = nums[min] + nums[max];

			//最大值最小值之和小于目标值时,删去最小值
			//最大值最小值之和小于目标值时,删去最大值
			if (num < target - nums[i]) {
				while (min < max&&nums[min] == nums[++min]);
			}
			else if (num > target - nums[i]) {
				while (min < max&&nums[max] == nums[--max]);
			}
			else {
				cout << target << "=" << nums[min] << "+" 
				     << nums[max] << "+" << nums[i] << endl;
				while (min < max&&nums[min] == nums[++min]);
				while (min < max&&nums[max] == nums[--max]);
			}
		}

		//排除相同值,避免重复
		while (i > 1 && nums[i] == nums[--i]);
	}
}

Spread

2Sum can also use a hash table to solve the complexity is O (n).
3Sum complexity of O (n ^ 2), if not better, then the method.

Published 63 original articles · won praise 73 · views 70000 +

Guess you like

Origin blog.csdn.net/jjwwwww/article/details/86477191