259. 3Sum Smaller

Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

For example, given nums = [-2, 0, 1, 3], and target = 2.

Return 2. Because there are two triplets which sums are less than 2:

[-2, 0, 1]
[-2, 0, 3]
Follow up:
Could you solve it in O(n2) runtime?

**解題思路 **
Binary Search Using n O(n2) runtime
注意: all hi in (lo, hi] will also satisfy the condition , 所以是 count += hi - lo 而不是count++;

    public int threeSumSmaller(int[] nums, int target) {
        int count = 0;
        Arrays.sort(nums);
        int len = nums.length;
        
        for (int i = 0; i < len - 2; i++) {
            int lo = i + 1, hi = len - 1;
            while (lo < hi) {
                if (nums[i] + nums[lo] + nums[hi] >= target) {
                    hi--;
                } else {
                    count += hi - lo;  // all hi in (lo, hi] will also satisfy the condition
                    lo++;
                }
            }
        }
        return count;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Given an array of n integers nums and a target, find the ...
    matrxyz閱讀 219評(píng)論 0 0
  • Given an array of n integers nums and a target, find the ...
    Jeanz閱讀 307評(píng)論 0 0
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,936評(píng)論 0 33
  • 我不知道有沒有人和我一樣,對(duì)自己目前生活的不滿,很想改變,但因?yàn)椴粔蜃月?,但又總是止于想,無行動(dòng)。于是也就...
    水紙舟閱讀 604評(píng)論 0 0
  • 人生頭一次接觸板繪吶,還用不太熟練,繪畫功底也不夠的哈,哈哈哈……笑出聲了,這圖一晚上擼出來的,以后再接再厲…
    大觸佡閱讀 267評(píng)論 0 0

友情鏈接更多精彩內(nèi)容