Array- CountTripletsSmallerThanSum
Leetcode - subarray-sum-equals-k

Leetcode - 3sum-closest

violet posted @ Feb 25, 2020 10:07:56 AM in 算法 with tags Algorithm 算法 Golang 3sum , 371 阅读

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

This is very similar to  Array- CountTripletsSmallerThanSum

Just keep track of abs of (result - sum) and return when the smallest one.

func threeSumClosest(nums []int, target int) int {
	if len(nums) == 0 {
		return 0
	}
	if len(nums) == 1 {
		return nums[0]
	}
	sort.Ints(nums)
	var result = nums[0] + nums[1] + nums[len(nums)-1]
	for i := 0; i < len(nums)-2; i++ {
		l := i + 1
		r := len(nums) - 1
		for l < r {
			sum := nums[i] + nums[l] + nums[r]
			if sum < target {
				l++
			} else {
				r--
			}
			if abs(result-target) > abs(sum-target) {
				result = sum
			}
		}
	}

	return result
}

func abs(a int) int {
	if a < 0 {
		return 0 - a
	}
	return a
}

 

 

PSC Result 2022 Comi 说:
Sep 06, 2022 10:06:59 PM

Right now there is a press announcement issued by Education Ministry Bangladesh for PSC Exam Result Date 2022, based on the announcement the PSC Result 2022 will be announced on 30th or 31st December 2022 in case of any early announcement the Grade-5 exam result announced on 24th December 2022 respectively for all education boards and all divisions in the country.According to the previous reports, PSC Result 2022 Comilla Board the PSC Result Date 2022 Comilla Board is also last week of December, however, we will update the official result date here after the official announcement by DPE, as per DPE previous five years result from the announcement of this year result will be announced likely on 30th or 31st December 2022.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter