Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

leetcode-16 最接近的三数和 #43

Open
ronghaoZHI opened this issue Jun 24, 2020 · 0 comments
Open

leetcode-16 最接近的三数和 #43

ronghaoZHI opened this issue Jun 24, 2020 · 0 comments

Comments

@ronghaoZHI
Copy link
Owner

leetcode 16

最接近的三数和 [-1, 2, 1, 4] target = 1;
output =2; (-1 + 2 + 1 = 2)

解题思路

  1. 暴力求解 复杂度 O(n 三次方)
  2. 类似 求三个数和; 排序 + 双指针 复杂度 O(n * log(n)_) + O(n 平方) = O(n 平方)
		function threeSum(nums, target) {
			nums.sort((a, b)=> a-b);
			let ans = nums[0] + nums[1] + nums[2];
			// let res = [nums[0], nums[1], nums[2]];
			for(let i = 0; i < nums.length; i++) {
				let left = i + 1, right = nums.length - 1;
				while(left < right) {
					let sum = nums[i] + nums[left] + nums[right];
					// 比较 差值大小, 更新 ans
					if(Math.abs(target - sum) < Math.abs(target - ans)) {
						// res = [nums[i], nums[left], nums[right]];
						ans = sum;
					}
					// 更新双指针
					if(sum > target) {
						right--;
					} else if(sum < target) {
						left++
					} else {
						return ans;
					}
				}
			}
			return ans;
		}
		console.log(threeSum([-1, 2, 1, 4], 1));
@ronghaoZHI ronghaoZHI changed the title leetcode leetcode 最接近的三数和 Jun 24, 2020
@ronghaoZHI ronghaoZHI changed the title leetcode 最接近的三数和 leetcode-16 最接近的三数和 Jun 24, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant