Saturday, August 23, 2014

3Sum Closet

Problem

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

For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

idea

  • 仍然采用两边夹逼的方法,即确定一个数start,然后指定end=num.size()-1和mid和start+1.然后根据num[start]+num[mid]+num[end]与target的关系来改变mid和end.让start循环遍历整个num.
  • 使用1个变量来记录当前距离target最小的组合
  • 不能跳过duplicates的element.

Solution


No comments:

Post a Comment