Wednesday, January 27, 2016

LeetCode Q16: 3Sum Cloest

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).


I first come up with a wrong solution which seems to be  very reasonable and actually similar to the final correct one. The idea in this wrong solution works by using two pointers pointing to the start and end of the sorted array. In every iteration, search the best result inbetween two pointers. Adjust (increase low point or decrease high pointer) the pointers according to the best result of current iteration. Actually so far I still can not figure out why this solution is wrong. Following is the code for this wrong soluton
  • Wrong solution


In correct solution, the idea is very similar to the one I described above. But difference is that, in this solution, in i=th iteration we keep the first pointer fixed at i-th element, and start a same searching process using two pointers as I described in the wrong solution. Following is the code for this correct solution 

  • Correct solution

No comments:

Post a Comment