3Sum Smaller

题目链接:https://leetcode.com/problems...

  1. sort,从小到大排序

  2. 固定第一个数字index = i,从后面的数字里选第二个第三个

  3. 后两个数字,用2 points来找,从j = i + 1, k = len() - 1开始:

    • if n[j] + n[k] < target - n[i]: count += (k-i), j++
      因为所有(j+1, k)之间的数和n[j]组合都< target - n[i]

    • if n[j] + n[k] >= target - n[i]: k--

public class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        if(nums == null || nums.length < 3) return 0;
        // sort first
        Arrays.sort(nums);
        /* enumerate 1st num: k
         * 2 points find 2nd, 3rd
         * initial: i = k + 1, j = len(nums) - 1
         * case 1: n[i] + n[j] < target - n[k]: count += j - i, i++
         * case 2: > : j--
         */
        int count = 0;
        for(int k = 0; k < nums.length - 2; k++) {
            int i = k + 1, j = nums.length - 1;
            while(i < j) {
                if(nums[i] + nums[j] >= target - nums[k]) j--;
                else {
                    count += j - i;  i++;
                }
            }
        }
        return count;
    }
}

lulouch13
13 声望6 粉丝

« 上一篇
LRU & LFU Cache
下一篇 »
Word Abbreviation