LeetCode combat -. Task05 and the number of the nearest three

Title:
Given an array comprising n integers and a target nums target. Nums identify the three integers, and a target such that their closest. The three numbers and return. Each group assumes that there is only input the only answer.

Example:

例如,给定数组 nums = [-121-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

Algorithm:
firstly sorted, and then traverse the primary array, the array corresponding to identify the location where the target is defined as the left and right around the target pointers two, left and right, respectively, and comparing the difference between the target select the smaller of as a result added to the result, the corresponding pointer is moved to the left or right, the comparison cycle, the final result obtained.

time complexity: O ( n 2 ) O (n ^ 2)
space complexity: O ( n ) O (n)

Code:

class Solution 
{
	public:
  	int threeSumClosest(vector<int>& nums, int target) 
	{
		sort(nums.begin(), nums.end());
		if(nums.size()<3) return 0;
		int ans = nums[0] + nums[1] + nums[2];
		for (int i = 0; i < nums.size(); i++)
		{
			int left = i + 1, right = nums.size() - 1;
			while (left < right)
			{
				int sum = nums[left] + nums[right] + nums[i];
				if (abs(target - sum) < abs(target - ans)) ans = sum;
				if (sum > target) right--;
				else if (sum < target) left++;
				else return ans;
			}
		}
		return ans;
	}
};

Results of the:
Here Insert Picture Description
Here Insert Picture Description

Published 95 original articles · won praise 28 · views 2406

Guess you like

Origin blog.csdn.net/qq_42093469/article/details/104673396