LeetCode-3Sum Smaller

每次外層循環固定住一個數字, 然後剩下兩個使用two pointer方法 每次初始化成頭和尾 然後根據大小挪動一次

public class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        if ( nums == null || nums.length < 3 )
            return 0;
        Arrays.sort ( nums );
        int count = 0;
        for ( int i = 0; i < nums.length - 2; i ++ ){
            int p1 = i + 1;
            int p2 = nums.length - 1;
            while ( p1 < p2 ){
                if ( nums [ p1 ] + nums [ p2 ] < target - nums[ i ] ){
                    count += p2 - p1;
                    p1 ++;
                }
                else{
                    p2 --;
                }
            }
        }
        return count;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章