<commit_before><commit_msg>3Sum Closest: solution same as 3sum<commit_after>/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function(nums, target) {
  // first sort, then use 2sum method
  nums.sort(function (a, b) {
    return a - b;
  })

  var len = nums.length;
  var min = nums[0] + nums[1] + nums[2];
  var minDiff = Math.abs(min - target);
  // suppose length must >= than 3
  if (nums.length === 3) return min;

  for (var i = 0; i < len; i++) {
    var find = target - nums[i];

    // two pointer, narrow to find the target
    var low = i + 1;
    var high = len - 1;

    while(low < high) {
      var sum = nums[low] + nums[high];
      var diff = Math.abs(sum - find);

      if (diff === 0) return target;

      if (diff < minDiff) {
        min = sum + nums[i];
        minDiff = diff;
      }

      if(sum < find) {
        low += 1;
      } else {
        high = high - 1;
      }
    }
  }

  return min;
};

var eq = require('assert').equal;

// -4 -1 1 2, 1
eq(threeSumClosest([-1, 2, 1, -4], 1), 2);
eq(threeSumClosest([-1, 2, 1], 4), 2);
eq(threeSumClosest([-1, 2, 1, 1], 1), 1);
eq(threeSumClosest([0,2,1,-3], 1), 0)
{'fraction_non_alphanumeric': 0.17809364548494983, 'fraction_numerical': 0.03511705685618729, 'mean_word_length': 2.2615803814713895, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4176236', 'n_tokens_mistral': 499, 'n_tokens_neox': 462, 'n_words': 139}