13. Two Pointer


兩個指針的問題:通過2個指針同步或不同步的移動,得到結果。時間復雜度一般會降低一個數量級。

適用于排好序的情況


86. Partition List
解析: 使用x進行劃分,小的在前面,大的在后面,x兩邊的相對順序不變。
邊界:鏈表為空
思路:兩個指針,一個負責小于x的情況,一個負責大于等于x的情況,之后連起來即可。注意!!!使用創建ListNode的對象,返回該對象的next
時間復雜度:O(n)
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode leftHead = ListNode(INT_MIN);
        ListNode rightHead = ListNode(INT_MIN);
        ListNode *left = &leftHead, *right = &rightHead;
        while (head) {
            if (head->val < x) {
                left->next = head;
                left = left->next;
            } else {
                right->next = head;
                right = right->next;
            }
            head = head->next;
        }
        left->next = rightHead.next;
        right->next = NULL;
        return leftHead.next;
    }
};

88. Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
使用兩個指針,本體需要原地,所以從后往前,最后只需將nums2加入。
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    int i = m - 1, j = n - 1, k = m + n - 1;
    while (i >= 0 && j >= 0) {
        if (nums1[i] > nums2[j]) {
            nums1[k--] = nums1[i--];
        } else {
            nums1[k--] = nums2[j--];
        }
    }
    while (j >= 0) {
        nums1[k--] = nums2[j--];
    }
}

11. Container With Most Water
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.
解析: abs(i-j)*min(nums[i],nums[j]) 的最大值
邊界:輸入數組大小小于2
思路:保留所有可能性,left在最左,right在最右。abs(i-j)肯定會變小,所有只需考慮高,高小于當前桶最高時,就要移動。
時間復雜度:O(n)
int maxArea(vector<int>& height) {
    int res;
    int left = 0, right = height.size()-1;
    while (left < right) {
        int h = min(height[left], height[right]);
        res = max(res,(right - left)*h);
        while (height[left] <= h && left < right) left++;
        while (height[right] <= h && left < right) right--;
    }
    return res;
}

167. Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
初始left = 0 , right = numbers.size() - 1. 偏大right往左移動,偏小left往右移動。
vector<int> twoSum(vector<int>& numbers, int target) {
    vector<int> res;
    if (numbers.size() < 2) {
        return res;
    }
    
    int left = 0, right = numbers.size() - 1;
    while (left < right) {
        if(target == numbers[left] + numbers[right]) {
            res.push_back(left+1);
            res.push_back(right+1);
            return res;
        }
        else if (target > numbers[left] + numbers[right]) {
            left++;
        }
        else {
            right--;
        }
    }
    return res;
}

15. 3Sum
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解析: 1. 先進行排序 2.取第i個元素的負為要求的和 3. 之后的處理和排好序的2SUM差不多。
注意的是重復問題,解決方法是 1. 開始時left = i + 1。 2. left有重復則left++,right有重復則right--,nums[i]有重復則i++。 3. nums[i] == nums[i+1] 時,i++
時間復雜度O(n^2)
vector<vector<int>> threeSum(vector<int>& nums) {
    vector<vector<int>> res;
    std::sort(nums.begin(),nums.end());
    for (int i = 0; i < nums.size(); ++i) {
        int target = - nums[i];
        int left = i + 1, right = nums.size() - 1;
        while(left < right) {
            if (target == nums[left] + nums[right]) {
                vector<int> tmp = {nums[i],nums[left],nums[right]};
                res.push_back(tmp);
                while (left < right && nums[left] == tmp[1]) left++;
                while (left < right && nums[right] == tmp[2]) right--;
            } else if (target > nums[left] + nums[right]) {
                left++;
            } else {
                right--;
            }
        }
        while(i < nums.size() - 1 && nums[i] == nums[i+1]) {
            i++;
        }
    }
    return res;
}

16. 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解析: 和3SUM類似,取三個數值和與目標值最近的。
思路:需要逼近目標值可能的情況,排序+左右2個指針,去逼近目標值即可。left = i + 1,避免了重復取值。
時間復雜度:O( n^2 ),如果挨個遍歷則是O(n^3)
int threeSumClosest(vector<int>& nums, int target) {
    std::sort(nums.begin(),nums.end());
    
    int span = INT_MAX, closet = INT_MIN;
    for (int i = 0; i < nums.size(); ++i) {
        int left = i + 1, right = nums.size() - 1;
        while (left < right) {
            int sum = nums[i] + nums[left] + nums[right];
            if (sum == target) {
                return target;
            } else if (sum > target) {
                while(left < right && nums[right] == nums[right-1]) right--;
                right--;
            } else {
                while(left < right && nums[left] == nums[left+1]) left++;
                left++;
            }
            if (abs(sum - target) <= span) {
                span = abs(sum - target);
                closet = sum;
            } 
        }
    }
    return closet;
}

18. 4Sum
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]
解析: 3Sum的變種,求4個數值的和等于目標值。
思路:先排序,4個數值從小到大,前2個用for,后2個使用2個指針。需要注意的是:1. 命中時,left和right移動到不等于與之前值不同的位置 2. for循環中的去重要在每次循環的結束位置,這樣就會考慮到重復值的開頭和結尾,中間部分去掉。
注意:每層循環的去重,i層,j層,2指針層。套路是去重放在后面,特別是2指針層的去重,要注意使用臨時變量保存結果,去重時和臨時變量進行比較。
vector<vector<int>> fourSum(vector<int>& nums, int target) {
    vector<vector<int>> res;
    if (nums.size() < 4) {
        return res;
    }
    std::sort(nums.begin(), nums.end());
    for (int i = 0; i < nums.size(); ++i) {
        for (int j = i + 1; j < nums.size(); ++j) {
            
            int t = target - nums[i] - nums[j];
            int left = j + 1, right = nums.size() -1 ;
            while (left < right) {
                int sum = nums[left] + nums[right];
                if (t == sum) {
                    vector<int> tmp = { nums[i],nums[j],nums[left],nums[right] };
                    res.push_back(tmp);
                    while (left < right && nums[left] == tmp[2]) left++;
                    while (left < right && nums[right] == tmp[3]) right--;
                }
                else if (t < sum) {
                    right--;
                }
                else {
                    left++;
                }
            }
            while (j < nums.size() - 1 && nums[j] == nums[j + 1]) j++;
        }
        while (i < nums.size() - 1 && nums[i] == nums[i + 1]) i++;
    }
    return res;
}

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?
解析: 求3個數值和比目標值小的全部情況。
邊界:輸入數組大小小于3
思路:sum >= target時,right左移。sum < target時,共有right-left中情況命中(sum[i]、left、從right到left的后一個),left右移。
時間復雜度:O(n^2 ),如果挨個遍歷則是O(n^3 )
int threeSumSmaller(vector<int>& nums, int target) {
    if (nums.size() < 3) {
        return 0;
    }
    std::sort(nums.begin(), nums.end());

    int res = 0;
    for (int i = 0; i < nums.size(); ++i) {
        int left = i + 1, right = nums.size() - 1;
        while (left < right) {
            int sum = nums[i] + nums[left] + nums[right];
            if (sum >= target) {
                right--;
            }
            else {
                res += right - left;
                left++;
            }
        }
    }
    return res;
}

75. Sort Colors
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note:
You are not suppose to use the library's sort function for this problem.
三種元素按類別劃分并排序
void sortColors(vector<int>& nums) {
    int left = 0, right = nums.size() - 1, i = 0;
    while (i <= right) {
        while (nums[i] == 2 && i < right) swap(nums[i], nums[right--]);
        while (nums[i] == 0 && i > left) swap(nums[i], nums[left++]);
        ++i;
    }
}

42. Trapping Rain Water
解析: int數組,求這些數值構成的桶盛水的大小。
邊界:數組大小大于2
思路:這道題時間復雜度為O(n)的情況比較難想,主要是要確定兩個值能構成桶的邊,而且桶的邊是可以移動的。使用left、right2個指針,誰小誰往中間湊,誰大誰不動,這就確定了桶的1條邊maxLeft或者maxRight。當移動過程中的值 >= 當前邊時,小于maxLeft或maxRight,差值就是該位置盛水的大小。
時間復雜度:O(n)
int trap(vector<int>& height) {
    if (height.size() < 2) return 0;
    int left = 0, right = height.size() - 1;
    int maxLeft = height[left], maxRight = height[right];
    int res = 0;
    
    while (left < right) {
        if (height[left] < height[right]) {
            maxLeft = max(maxLeft, height[++left]);
            res += maxLeft - height[left];
        } else {
            maxRight = max(maxRight, height[--right]);
            res += maxRight - height[right];
        }
    }
    
    return res;
}

26. Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
去除有序數組中重復元素,使用2個指針可以值遍歷一次就完成,而且邏輯清晰。left負責從左向右新增不同元素,right負責遍歷整個數組。right遍歷到不同于當前left時,left向前移動并保存新元素。
int removeDuplicates(vector<int>& nums) {
    int left = 0, right = 0;
    while (right < nums.size()) {
        if(left < 1 || nums[right] > nums[left - 1]) {
            nums[left++] = nums[right];
        }
        right++;
    }
    
    return left;
}

80. Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
去除數組中重復元素,每個元素最多出現2次
int removeDuplicates(vector<int>& nums) {
    int left = 0, right = 0;
    while (right < nums.size()) {
        if (right < 2 || nums[right] > nums[left - 2]) {
            nums[left++] = nums[right];
        }
        right++;
    }
    return left;
}

19. Remove Nth Node From End of List
解析: 鏈表中移除倒數第N個元素。
邊界:鏈表為空
思路:兩個指針,距離為N即可,當right為空時,left在要去除的位置。需要注意的是最好另外有個新指針res指向給出鏈表的頭部,返回res.next(),可以統一處理結果為空的情況。
時間復雜度:O(n)
ListNode* removeNthFromEnd(ListNode* head, int n) {
    ListNode res = ListNode(-1);
    res.next = head;
    ListNode *left = head, *right = head, *last = &res;
    for (int i = 0; i < n && right != NULL; ++i) {
        right = right -> next;
    }
    
    while (right != NULL) {
        last = left;
        left = left -> next;
        right = right -> next;
    }
    last -> next = left -> next;
    while (left != NULL) {
        left = left -> next;
    }
    return res.next;
}

209. Minimum Size Subarray Sum
解析: 求使得連續子數組和>x的最短連續子數組。
邊界:全部和<x
思路:連續數組和>x時,才嘗試移動left。
時間復雜度:O(n^2)
int minSubArrayLen(int s, vector<int>& nums) {
    int left = 0, right = 0, sum = 0, res = INT_MAX;
    while (right < nums.size()) {
        sum += nums[right++];
        while (sum >= s) {
            res = min(res, right - left);
            sum -= nums[left++];
        }
    }
    return res == INT_MAX ? 0 : res;
}

61. Rotate List
解析: 旋轉鏈表,將鏈表從右往左的第k個節點作為分割進行旋轉。注意:
邊界:全部和<x
思路:遍歷鏈表,統計鏈表長度,使鏈表收尾相接!!!求出實際分割點,進行分割。
時間復雜度:O(n^2)
ListNode* rotateRight(ListNode* head, int k) {
    if (!head) return NULL;
    
    ListNode *tail = head;;
    int length = 1;
    while(tail -> next){
        tail = tail -> next;
        length++;
    }
    tail -> next = head;
    if (k %= length) {
    for (int i = 0; i < length - k; ++i) {
        tail = head;
        head = head -> next;
    }
    }
    tail -> next = NULL;
    
    return head;
    
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,333評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,491評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,263評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,946評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,708評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,186評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,409評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,939評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,774評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,976評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,209評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,641評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,872評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,650評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,958評論 2 373

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,762評論 0 33
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,717評論 18 399
  • 1.把二元查找樹轉變成排序的雙向鏈表 題目: 輸入一棵二元查找樹,將該二元查找樹轉換成一個排序的雙向鏈表。 要求不...
    曲終人散Li閱讀 3,341評論 0 19
  • (一)他鄉說故鄉 家鄉,每當想起這兩個字,覺得特別親切,那里有一座老房子,熟悉的房子里住著我的...
    雙生夕閱讀 404評論 3 4
  • 佳佳的寒假作業有一項是分享,分享什么呢,當然是書啰…… 佳佳喜歡的兩本書 一本翻翻書,知識以樂趣的方式呈現。另一本...
    Coffee6點5閱讀 380評論 0 0