兩個指針的問題:通過2個指針同步或不同步的移動,得到結果。時間復雜度一般會降低一個數量級。
適用于排好序的情況
解析: 使用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;
}
};
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--];
}
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
}
解析: 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;
}
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;
}
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;
}
解析: 鏈表中移除倒數第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;
}
解析: 求使得連續子數組和>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;
}
解析: 旋轉鏈表,將鏈表從右往左的第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;
}