Two Pointers first 50 (3 - 923)

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

287. Find the Duplicate Number Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2

1. use set to record the value 2. sort and find. (faster) class Solution { public: int findDuplicate(vector<int>& nums) { sort(nums.begin(), nums.end()); for(int i = 1;i < nums.size(); i ++) { if(nums[i] == nums[i-1]) return nums[i]; } return -1; } int findDuplicate1(vector<int>& nums) { //use set int size = nums.size(); set<int> arr; for(auto& num: nums) { if(arr.find(num) != arr.end()) return num; arr.insert(num); } return -1; } };

28. Implement strStr() Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2

class Solution { public: int strStr(string haystack, string needle) { if(needle.length() == 0) return 0; int m = haystack.length(); int n = needle.length(); int l = 0; int r = 0; for(; l < m; l ++) { if(haystack.substr(l, n) == needle) return l; } return -1; } };

345. Reverse Vowels of a String Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Input: "hello" Output: "holle"

class Solution { public: string reverseVowels(string s) { int len = s.length(); int l = 0; int r = len - 1; while(l <= r) { if(! isVowel(s[l])) l ++; else if(! isVowel(s[r])) r --; else { swap(s[l], s[r]); l ++; r --; } } return s; } bool isVowel(char ch) { char c = tolower(ch); return c == 'a' || c =='e' || c == 'i' || c == 'o' || c == 'u'; } };

845. Longest Mountain in Array Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold: B.length >= 3 There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] Input: [2,1,4,7,3,2,5] Output: 5

first, we ignore the first part of non increasing part. Then we go through the increasing part, if following by equal part, ignore the non increasing part. else loop through the decreasing part and get res. class Solution { public: int longestMountain(vector<int>& A) { int size = A.size(); if(size <3) return 0; int ind = 1; while(ind < size && A[ind] <= A[ind-1]) ind ++; if(ind == size) return 0; int res = 0; int start = ind - 1; while(ind < size) { while(ind < size && A[ind] > A[ind-1]) ind ++; if(ind == size) break; if(A[ind] == A[ind - 1]) { while(ind < size && A[ind] <= A[ind-1]) ind ++; start = ind - 1; continue; } else { while(ind < size && A[ind] < A[ind-1]) ind ++; res = max(res, ind - start); start = ind - 1; } } return res; } };

524. Longest Word in Dictionary through Deleting Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. Example 1: Input: s = "abpcplea", d = ["ale","apple","monkey","plea"] Output: "apple"

for each in dict, we check whether can be formed using string. -> two pointers class Solution { public: string findLongestWord(string s, vector<string>& d) { string res = ""; for(auto& str: d) { if(valid(s, str) && (str.length() > res.length() || str.length() == res.length() && str < res)) { res = str; } } return res; } bool valid(string s1, string s2) { int m = s1.length(); int n = s2.length(); int j = 0; for(int i = 0; i < m && j < n; i ++) { if(s1[i] == s2[j]) j ++; } return j == n; } };

457. Circular Array Loop You are given a circular array nums of positive and negative integers. If a number k at an index is positive, then move forward k steps. Conversely, if it's negative (-k), move backward k steps. Since the array is circular, you may assume that the last element's next element is the first element, and the first element's previous element is the last element. Determine if there is a loop (or a cycle) in nums. A cycle must start and end at the same index and the cycle's length > 1. Furthermore, movements in a cycle must all follow a single direction. In other words, a cycle must not consist of both forward and backward movements. Input: [2,-1,1,2,2] Output: true Explanation: There is a cycle, from index 0 -> 2 -> 3 -> 0. The cycle's length is 3.

for each index i, use two pointers j, k. j is slower pointer, every time move 1 step. k is faster pointer, every time move 2 step. check when j == k. class Solution { private: vector<int> nums; int size; public: bool circularArrayLoop(vector<int>& nums) { size = nums.size(); this -> nums = nums; for(int i = 0; i < size; i ++) { if(nums[i] == 0) continue; int j = i; int k = i; while(nums[k] * nums[i] > 0 && nums[next(k)] * nums[i] > 0) { j = next(j); k = next(next(k)); if(j == k) { if(next(j) == j) break; else return true; } } int tmp = next(i); while(nums[tmp] * nums[i] >0) { nums[tmp] = 0; tmp = next(tmp); } } return false; } int next(int ind) { int val = nums[ind]; int nextInd = val + ind; if(nextInd >= 0) return nextInd % size; else { int factor = nextInd / size; return (nextInd + (-factor + 1) * size) % size; } return -1; } };

844. Backspace String Compare Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Example 1: Input: S = "ab#c", T = "ad#c" Output: true

if ch == '#' check and pop back.else append class Solution { public: bool backspaceCompare(string S, string T) { string s1 = getStr(S); string s2 = getStr(T); return s1 == s2; } string getStr(string s) { string res; for(auto& ch: s) { if(ch == '#') { if(!res.empty()) res.pop_back(); } else res += ch; } return res; } };

828. Unique Letter String A character is unique in string S if it occurs exactly once in it. For example, in string S = "LETTER", the only unique characters are "L" and "R". Let's define UNIQ(S) as the number of unique characters in string S. For example, UNIQ("LETTER") = 2. Given a string S with only uppercases, calculate the sum of UNIQ(substring) over all non-empty substrings of S. If there are two or more equal substrings at different positions in S, we consider them different. Since the answer can be very large, return the answer modulo 10 ^ 9 + 7. Input: "ABC" Output: 10 Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC". Evey substring is composed with only unique letters.

instead of get substring and count unique chars, we count how many times current char occurs in substring. For example: ABC, A happens in A, AB, ABC. ABA: A happens in A, AB. class Solution { private: int MOD = 1e9 + 7; public: int uniqueLetterString(string s) { int len = s.length(); unordered_map<char, vector<int> > indMap; for(int i = 0; i < len; i ++) { indMap[s[i]].push_back(i); } long res = 0; for(auto& [ch, arr]: indMap) { for(int j = 0; j < arr.size(); j ++) { int prev = j == 0? -1: arr[j-1]; int next = j == arr.size() - 1? len: arr[j+1]; long count = (arr[j] - prev) * (next - arr[j]) % MOD; res = (res + count) % MOD; } } return res; } };

632. Smallest Range You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c. Example 1: Input:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] Output: [20,24]

like array merge. From left to right, we get the current mins of each array and put into map. get the current segment and add the index of min. struct comparer { bool operator() (const pair<int,int>& v1, const pair<int,int>& v2) const { return v1.second < v2.second || (v1.second == v2.second && v1.first < v2.first); } }; class Solution { public: vector<int> smallestRange(vector<vector<int>>& nums) { int size = nums.size(); if(size == 0) return {}; if(size == 1) return {nums[0][0], nums[0][0]}; vector<int> ids(size, 0); map< pair<int,int>, bool, comparer> numMap; for(int i = 0; i < size; i ++) { if(nums[i].empty()) return {}; numMap[ pair(i, nums[i][0]) ] = true; } vector<int> res = {0, INT_MAX}; while(true) { pair<int, int> minV = numMap.begin()-> first; pair<int, int> maxV = (-- numMap.end()) -> first; int ind = minV.first; if(maxV.second - minV.second < res[1] - res[0]) { res = {minV.second, maxV.second}; } ids[ind] ++; if(ids[ind] >= nums[ind].size()) return res; numMap.erase(minV); numMap[ pair(ind, nums[ind][ids[ind]])] = true; } return {0, 0}; } };

283. Move Zeroes Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0]

maintain l, r two pointers, if nums[r] != 0, swap with l. class Solution { public: void moveZeroes(vector<int>& nums) { int size = nums.size(); int l = 0; for(int r = 0; r < size; r ++) { if(nums[r] != 0) { swap(nums, l ,r ); l ++; } } } void swap(vector<int>& nums, int i, int j) { int tmp = nums[i]; nums[i] =nums[j]; nums[j] = tmp; } };

125. Valid Palindrome Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true

only look for digit and alpha class Solution { public: bool isPalindrome(string s) { int len = s.length(); int l = 0; int r = len - 1; while(l <= r) { char c1 = s[l]; char c2 = s[r]; if(valid(c1) && valid(c2)) { if(tolower(c1) != tolower(c2)) return false; l ++; r --; } else if(!valid(c1)) l ++; else if(!valid(c2)) r --; } return true; } bool valid(char ch) { return isalpha(ch) || isdigit(ch); } };

487. Max Consecutive Ones II Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0. Example 1: Input: [1,0,1,1,0] Output: 4

record l, r two pointers and count of 1s. if(r - l + 1 - count) > 1, then move l forward. class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int size = nums.size(); int l = 0; int count = 0; int res = 0; for(int r = 0; r < size; r ++) { if(nums[r] == 1) count ++; else { int convert = r - l + 1 - count; if(convert > 1) { while(convert > 1) { if(nums[l] == 1) count --; l ++; convert = r - l + 1 - count; } } } res = max(res, r-l+1); } 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. Input: numbers = [2,7,11,15], target = 9 Output: [1,2]

standard two pointers. class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int size = nums.size(); int l = 0; int r = size -1; while(l < r) { if(nums[l] + nums[r] == target) return {l + 1, r + 1}; else if(nums[l] + nums[r] < target) l ++; else r --; } return {}; } };

838. Push Dominoes After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. Input: ".L.R...LR..L.." Output: "LL.RR.LLRRLL.."

there are 4 combinations: LxxL, LxxR, RxxL, RxxR. we record the prev char, and prev index. if prev == 'R' and current = 'L' , we need to calc. if prev == 'L' and current . = 'L', fall left. if prev == 'R' and current . = 'R', fall right class Solution { public: string pushDominoes(string s) { int len = s.length(); if(len == 0 || s.find(".") == -1) return s; char prev = s[0]; int prevInd = 0; string res = s; for(int i = 1; i < len; i ++) { char ch = s[i]; if(ch == 'L') { if(prev == '.' || prev == 'L') { for(int j = prevInd; j <= i; j ++) res[j] = 'L'; } else if(prev == 'R') { int count = (i - prevInd - 1) / 2; if((i - prevInd + 1) % 2 == 1) res[(prevInd + count + 1)] = '.'; for(int k = 1; k <= count; k ++) { res[prevInd + k] = 'R'; res[i - k] = 'L'; } } prevInd = i; prev = 'L'; } else if(ch == 'R') { if(prev == 'R') { for(int j = prevInd; j <= i; j ++) res[j] = 'R'; } prevInd = i; prev = 'R'; } } if(prev == 'R') { for(int j = prevInd; j < len; j ++) res[j] = 'R'; } return res; } };

923. 3Sum With Multiplicity Given an integer array A, and an integer target, return the number of tuples i, j, k such that i < j < k and A[i] + A[j] + A[k] == target. As the answer can be very large, return it modulo 10^9 + 7. Input: A = [1,1,2,2,3,3,4,4,5,5], target = 8 Output: 20 Explanation: Enumerating by the values (A[i], A[j], A[k]): (1, 2, 5) occurs 8 times; (1, 3, 4) occurs 8 times; (2, 2, 4) occurs 2 times; (2, 3, 3) occurs 2 times.

this involves multiply element. 1. calc xxx style 2. for each value , similar to 3sum, but need to consider xyy. 3. two pointers to solve xyz style class Solution { private: int MOD = 1e9 + 7; public: int threeSumMulti(vector<int>& A, int target) { map<int, int> countMap; vector<int> arr; for(auto& num: A) countMap[num] ++; for(auto& [num, count]: countMap) arr.push_back(num); long res = 0; int size = arr.size(); if(target % 3 == 0 && countMap[target / 3] >= 3) { //xxx int v = target / 3; long c = countMap[v]; res = (res + (c *(c-1) *(c-2)) / 6) % MOD; } for(int i = 0; i < size; i ++) { int val = arr[i]; long c = countMap[val]; int newT = target - val; if(newT % 2 == 0 && newT / 2 != val && countMap[newT / 2] >= 2) { //xyy int c1 = countMap[newT / 2]; int v1 = c1 * (c1-1) / 2; res = (res + v1 * c) % MOD; } int l = i + 1; int r = size - 1; //xyz while(l < r) { if(arr[l] + arr[r] == newT) { res = (res + c * countMap[arr[l]] * countMap[arr[r]]) % MOD; l ++; r --; } else if(arr[l] + arr[r] < newT) l ++; else r --; } } return res; } };

904. Fruit Into Baskets You start at any tree of your choice, then repeatedly perform the following steps: Add one piece of fruit from this tree to your baskets. If you cannot, stop. Move to the next tree to the right of the current tree. If there is no tree to the right, stop. Input: [1,2,3,2,2] Output: 4

this is the same as longest unique substring. 1. use l, r two pointers. if unique number > 2, move l forward. 2. record the latest index for number, when unique number >2, delete the number with smallest index. class Solution { public: int totalFruit(vector<int>& tree) { int size = tree.size(); unordered_map<int, int> indMap; int res = 0; int start = 0; for(int i = 0; i< size; i ++) { indMap[tree[i]] = i; if(indMap.size() > 2) { int minInd = INT_MAX; for(auto& [val, ind]: indMap) { minInd = min(minInd, ind); } int toDelete = tree[minInd]; indMap.erase(toDelete); start = minInd + 1; } res = max(res, i - start + 1); } return res; } int totalFruit1(vector<int>& tree) { // use two pointers int size = tree.size(); int l = 0; int r = 0; int res = 0; unordered_map<int, int> countMap; for(; r < size ; r ++) { countMap[tree[r]] ++; if(countMap.size() > 2) { while(countMap.size() > 2) { countMap[tree[l]] --; if(countMap[tree[l]] == 0) countMap.erase(tree[l]); l ++; } } res = max(res, r - l + 1); } return res; } };

344. Reverse String Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"]

typical two pointers. class Solution { public: void reverseString(vector<char>& s) { int len = s.size(); int l = 0; int r = len - 1; while(l <= r) { char ch = s[l]; s[l] = s[r]; s[r] = ch; l ++; r --; } } };

567. Permutation in String Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. Input: s1 = "ab" s2 = "eidbaooo" Output: True

use countmap to compare whether permutation. use sliding window to get current countmap. class Solution { public: bool checkInclusion(string s1, string s2) { unordered_map<char, int> countMap; int m = s1.length(); for(auto& ch: s1) countMap[ch] ++; unordered_map<char, int> map1; for(int i = 0; i < s2.length(); i ++) { if(i < m) map1[s2[i]] ++; else { map1[s2[i]] ++; map1[s2[i-m]] --; if(map1[s2[i-m]] == 0) map1.erase(s2[i-m]); } if(map1.size() == countMap.size() && same(countMap, map1)) return true; } return false; } bool same(unordered_map<char, int>& map1, unordered_map<char, int>& map2) { for(auto& [ch, count]: map1) { if(map2.find(ch) == map2.end() || map2[ch] != count) return false; } return true; } };

424. Longest Repeating Character Replacement Given a string s that consists of only uppercase English letters, you can perform at most k operations on that string. In one operation, you can choose any character of the string and change it to any other uppercase English character. Find the length of the longest sub-string containing all repeating letters you can get after performing the above operations. Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa.

use l, r pointer. r - l + 1 is the total count. maxCount is the current main char count. total - maxCount is the convert count. while > k, l ++. class Solution { public: int characterReplacement(string s, int k) { int res = 0; unordered_map<char, int> countMap; int l = 0; int maxCount = 0; for(int i = 0; i < s.length(); i ++) { countMap[s[i]] ++; maxCount = max(maxCount, countMap[s[i]]); int total = i - l + 1; int convert = total - maxCount; if(convert <= k) res = max(res, total); else { while(i - l + 1 - maxCount > k) { countMap[s[l]] --; l ++; } } } return res; } };

209. Minimum Size Subarray Sum Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. Example: Input: s = 7, nums = [2,3,1,2,4,3] Output: 2

use l, r two pointers. class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { int size = nums.size(); int l = 0; int sum = 0; int res = INT_MAX; for(int r = 0; r < size; r ++) { sum += nums[r]; if(sum >= s) { while(sum >= s) { res = min(res, r - l + 1); sum -= nums[l]; l ++; } } } return res == INT_MAX? 0: 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. Input: nums = [-2,0,1,3], and target = 2 Output: 2 Explanation: Because there are two triplets which sums are less than 2: [-2,0,1] [-2,0,3]

use two pointers, when l, r and arr[l] + arr[r] < newTarget, count += r - l and move l ++. class Solution { public: int threeSumSmaller(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); int res = 0; for(int i = 0; i < nums.size(); i ++) { int l = i +1; int r = nums.size() - 1; int newTarget = target - nums[i]; while(l < r) { if(nums[l] + nums[r] < newTarget) { res += r - l; l ++; } else r --; } } return res; } };

881. Boats to Save People The i-th person has weight people[i], and each boat can carry a maximum weight of limit. Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.) Input: people = [3,5,3,4], limit = 5 Output: 4

we put max and min into one boat if can. class Solution { public: int numRescueBoats(vector<int>& people, int limit) { int size = people.size(); sort(people.begin(), people.end()); int l = 0; int r = size - 1; int res = 0; while(l <=r ) { if(l != r && people[l] + people[r] <= limit) { l ++; r --; } else r --; res ++; } return res; } };

826. Most Profit Assigning Work We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job. Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i]. Every worker can be assigned at most one job, but one job can be completed multiple times. Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7] Output: 100 Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.

we sort the (difficulty, profit) pair by difficulty, and store in set. use lower_bound to get the difficulty. typedef pair<int,int> pi; struct comparer { bool operator() (const pi& p1, const pi& p2) const { return p1.second < p2.second || (p1.second == p2.second && p1.first < p2.first); } }; class Solution { public: int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) { int size = difficulty.size(); set< pi, comparer > pairs; for(int i = 0; i < size; i ++) { pairs.insert( pair(profit[i], difficulty[i]) ); } unordered_map<int, int> profitMap; int maxP = 0; for(auto& wPair: pairs) { maxP = max(maxP, wPair.first); profitMap[wPair.second] = maxP; } int res = 0; for(auto& w: worker) { auto ite = pairs.lower_bound( pair(0,w) ); if(ite == pairs.end() || ite->second > w) { --ite; } res += profitMap[ite->second]; } return res; } };

723. Candy Crush If three or more candies of the same type are adjacent vertically or horizontally, "crush" them all at the same time - these positions become empty. After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. (No new candies will drop outside the top boundary.) After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps. If there does not exist more candies that can be crushed (ie. the board is stable), then return the current board.

we use colMap to record the crashing rows of each col. then during crashing, we use two pointers to remove the unused ones. class Solution { private: int rows; int cols; vector< vector<int> >delta = {{-1, 0}, {1, 0}, {0, -1}, {0,1}}; public: vector<vector<int>> candyCrush(vector<vector<int>>& board) { rows = board.size(); cols = board[0].size(); while(true) { unordered_map<int, set<int>> colMap; for(int r = 0; r < rows; r ++) { for(int c = 0; c < cols; c ++) if(board[r][c] != 0) { int x = handleX(board, r, c); if(x >= 3) { for(int k = c; k < c + x; k ++) { colMap[k].insert(r); } } int y = handleY(board, r, c); if(y >= 3) { for(int k = r; k < r + y; k ++) { colMap[c].insert(k); } } } } if(colMap.empty()) return board; doCrush(board, colMap); } return board; } void doCrush(vector<vector<int>>& board, unordered_map<int, set<int>>& colMap) { for(int c = 0; c < cols; c ++) { int i = rows - 1; for(int j = rows-1; j >= 0; j --) { if(board[j][c] == 0) { break; } if(colMap[c].find(j) == colMap[c].end()) { board[i][c] = board[j][c]; i --; } } for(int k = i; k >= 0; k --) { board[k][c] = 0; } } } int handleX(vector<vector<int>>& board, int row, int col) { int res = 1; for(int c = col +1; c < cols; c ++) { if(board[row][c] == board[row][col]) res ++; else break; } return res; } int handleY(vector<vector<int>>& board, int row, int col) { int res = 1; for(int r = row +1; r < rows; r ++) { if(board[r][col] == board[row][col]) res ++; else break; } return res; } };

713. Subarray Product Less Than K Your are given an array of positive integers nums. Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k. Example 1: Input: nums = [10, 5, 2, 6], k = 100 Output: 8 Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].

we use l, r two pointers. every time if prod < k, res += r - l + 1, else move l forward. class Solution { public: int numSubarrayProductLessThanK(vector<int>& nums, int k) { int size = nums.size(); if(size == 0 || k == 0) return 0; int res = 0; int l = 0; int prod = 1; for(int r = 0; r < size; r ++) { prod *= nums[r]; if(prod >= k) { while(l <= r && prod >= k) { prod /= nums[l]; l ++; } } res += (r - l + 1); } return res; } };

532. K-diff Pairs in an Array Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. Example 1: Input: [3, 1, 4, 1, 5], k = 2 Output: 2

we use map to record the countMap. class Solution { public: int findPairs(vector<int>& nums, int k) { if(k < 0) return 0; map<int, int> countMap; for(auto& num: nums) countMap[num] ++; int res = 0; for(auto& [num, count]: countMap) { count --; if(countMap.find(num + k) != countMap.end() && countMap[num + k] > 0) res ++; count ++; } return res; } };

763. Partition Labels A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts. Example 1: Input: S = "ababcbacadefegdehijhklij" Output: [9,7,8]

we use map to record the max index for char. when current index == maxInd, mean current loop is closed. class Solution { public: vector<int> partitionLabels(string s) { int len = s.length(); vector<int> res; unordered_map<char, int> indMap; for(int i = 0; i < len; i ++) indMap[s[i]] = i; int maxInd = -1; int l = 0; for(int i = 0; i < len; i ++) { char ch = s[i]; int currMax = indMap[ch]; maxInd = max(maxInd, currMax); if(i == maxInd) { res.push_back(i - l +1); maxInd = -1; l = i + 1; } } return res; } };


संबंधित स्टडी सेट्स

W1SQ: The Declaration of Independence

View Set

Microbiology Chapter 3 HW, Microbiology Chapter 4 Part 2 HW, Microbiology Chapter 4 Part 1 HW

View Set

Exam 3 Study Guide (Ch. 9, 13, 14, 16)

View Set

Anatomy- Chapter 7 Quizlet (actual test questions)

View Set

U.S. History chapter 4-9. Unit quiz 2

View Set

Diffusion, Osmosis and Active Transport

View Set

Health Chapter 1 : Field Underwriting Procedures

View Set