Solved LeetCode program · 16 of 1,000
#0016 · 3Sum Closest
Original English source
The nums is a list of -1, 2, 1, and -4. The target is 1. Sort nums. The last is the last position of nums. The best is 0. The bestdistance is 2147483647.
For every first from 0 to last.
The second is one more than first. The third is last.
Repeat while second is less than third.
The total is item first of nums plus item second of nums plus item third of nums. The difference is total minus target. If difference is less than 0, set difference to 0 minus difference. If difference is less than bestdistance, set bestdistance to difference, set best to total. If total is less than target, add 1 to second. If total is more than target, subtract 1 from third. If total is target, add 1 to second, subtract 1 from third.
Display best.
Expected stdout
2