Array forth 50

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

1151. Minimum Swaps to Group All 1's Together Given a binary array data, return the minimum number of swaps required to group all 1's present in the array together in any place in the array. Input: [1,0,1,0,1] Output: 1

same as the move stone problem. we get the index and count of 1, then check how many 1 are in place and the count needed to move. class Solution { public: int minSwaps(vector<int>& data) { //same as move stone int count = 0; vector<int> inds; for(int i = 0; i < data.size(); i ++) if(data[i] == 1) { count ++; inds.push_back(i); } if(count < 2) return 0; int res = INT_MAX; int l = 0; for(int i = 0; i < inds.size(); i ++) { while(inds[i] - inds[l] >= count) l ++; int inplace = i - l + 1; res = min(res, count - inplace); } return res; } };

1011. Capacity To Ship Packages Within D Days A conveyor belt has packages that must be shipped from one port to another within D days. The i-th package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days. Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5 Output: 15

binary search to get next check capacity, class Solution { public: int shipWithinDays(vector<int>& weights, int D) { int size = weights.size(); int maxV = -1; int sum = 0; for(auto& num: weights) { maxV = max(maxV, num); sum += num; } int l = maxV; int r = sum; while(l < r) { int mid = (l + r) / 2; if(!check(weights, mid, D)) l = mid+1; else r = mid; } return l; } bool check(vector<int>& weights, int val, int day) { int count = 1; int sum = 0; for(auto& num: weights) { if(sum + num > val) { count ++; sum = num; } else sum += num; } return count <= day; } };

1064. Fixed Point Given an array A of distinct integers sorted in ascending order, return the smallest index i that satisfies A[i] == i. Return -1 if no such i exists. Input: [-10,-5,0,3,7] Output: 3

binary search. class Solution { public: int fixedPoint(vector<int>& A) { int l = 0; int r = A.size() - 1; while(l < r) { int mid = (l + r) / 2; if(A[mid] < mid) l = mid+1; else r = mid; } if(l >= A.size()) return -1; return A[l] == l? l: -1; } };

1150. Check If a Number Is Majority Element in a Sorted Array Given an array nums sorted in non-decreasing order, and a number target, return True if and only if target is a majority element. A majority element is an element that appears more than N/2 times in an array of length N. Input: nums = [2,4,5,5,5,5,5,6,6], target = 5 Output: true

check and get mid, then expand. class Solution { public: bool isMajorityElement(vector<int>& nums, int target) { int size = nums.size(); int mid = (size-1) / 2; if(nums[mid] != target) return false; int l = mid; while(l >= 0 && nums[l] == target) l --; int r = mid; while(r < size && nums[r] == target) r ++; int cnt = r - l -1; return cnt > (size/2); } };

1160. Find Words That Can Be Formed by Characters You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words. Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6

class Solution { public: int countCharacters(vector<string>& words, string chars) { int res = 0; unordered_map<char,int> counts; for(auto& ch: chars) counts[ch] ++; for(auto& str: words) { if(valid(str, counts)) res += str.length(); } return res; } bool valid(string s, unordered_map<char,int>& counts) { unordered_map<char,int> tmp; for(auto& ch: s) tmp[ch] ++; for(auto& [ch, cnt]: tmp) if(counts[ch] < cnt) return false; return true; } };

1051. Height Checker Students are asked to stand in non-decreasing order of heights for an annual photo. Return the minimum number of students not standing in the right positions. (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.) Input: [1,1,4,2,1,3] Output: 3

class Solution { public: int heightChecker(vector<int>& heights) { int size = heights.size(); vector<int> sorted = heights; sort(sorted.begin(), sorted.end()); int res= 0; for(int i = 0; i< size; i ++) if(sorted[i] != heights[i]) res ++; return res; } };

999. Available Captures for Rook On an 8 x 8 chessboard, there is one white rook. There also may be empty squares, white bishops, and black pawns. These are given as characters 'R', '.', 'B', and 'p' respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces. The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies. Also, rooks cannot move into the same square as other friendly bishops. Return the number of pawns the rook can capture in one move.

class Solution { public: int numRookCaptures(vector<vector<char>>& board) { vector<int> pos; for(int i = 0; i < 8; i ++) { for(int j = 0; j< 8; j ++) { if(board[i][j] == 'R') { pos = {i, j}; break; } } } int res = 0; int x = pos[0]; while(x >= 0) { if(board[x][pos[1]] == 'B') break; else if(board[x][pos[1]] == 'p') { res ++; break; } x --; } x = pos[0]; while(x < 8) { if(board[x][pos[1]] == 'B') break; else if(board[x][pos[1]] == 'p') { res ++; break; } x ++; } int y = pos[1]; while(y >= 0) { if(board[pos[0]][y] == 'B') break; else if(board[pos[0]][y] == 'p') { res ++; break; } y --; } y = pos[1]; while(y < 8) { if(board[pos[0]][y] == 'B') break; else if(board[pos[0]][y] == 'p') { res ++; break; } y ++; } return res; } };

1074. Number of Submatrices That Sum to Target Given a matrix, and a target, return the number of non-empty submatrices that sum to target. A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2. Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'. Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 Output: 4

class Solution { public: int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) { int rows = matrix.size(); if(rows == 0) return 0; int cols = matrix[0].size(); int res = 0; for(int l = 0; l < cols; l ++) { vector<int> colArr(rows); for(int r = l; r < cols; r ++) { for(int i = 0; i < rows; i ++) { colArr[i] += matrix[i][r]; } unordered_map<int,int> counts; counts[0] ++; int sum = 0; for(auto& num: colArr) { sum += num; res += counts[sum - target]; counts[sum] ++; } } } return res; } };

1085. Sum of Digits in the Minimum Number Given an array A of positive integers, let S be the sum of the digits of the minimal element of A. Return 0 if S is odd, otherwise return 1. Input: [34,23,1,24,75,33,54,8] Output: 0

class Solution { public: int sumOfDigits(vector<int>& A) { sort(A.begin(), A.end()); string s= to_string(A[0]); int sum = 0; for(auto& ch: s) sum += ch - '0'; return sum % 2 == 0; } };

1018. Binary Prefix Divisible By 5 Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.) Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5. Input: [0,1,1] Output: [true,false,false]

class Solution { public: vector<bool> prefixesDivBy5(vector<int>& A) { int sum = 0; int size = A.size(); vector<bool> res(size); for(int i = 0; i < size; i ++) { sum = (sum * 2 + A[i]) % 5; res[i] = sum % 5 == 0; } return res; } };

989. Add to Array-Form of Integer For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1]. Given the array-form A of a non-negative integer X, return the array-form of the integer X+K. Input: A = [1,2,0,0], K = 34 Output: [1,2,3,4] Explanation: 1200 + 34 = 1234

class Solution { public: vector<int> addToArrayForm(vector<int>& A, int K) { string s = to_string(K); int len = s.length(); vector<int> arr(len); for(int i = 0; i<len; i ++) arr[i] = s[i] - '0'; int size = A.size(); int i = size-1; int j = len-1; vector<int> res(max(len, size)); int k = res.size() - 1; int flag = 0; while(i >= 0 || j >= 0) { int val = flag; if(i >= 0) val += A[i]; if(j >= 0) val += arr[j]; res[k--] = val % 10; flag = val / 10; i --; j --; } if(flag > 0) res.insert(res.begin(), flag); return res; } };

1040. Moving Stones Until Consecutive II Each turn, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone. In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone. The game ends when you cannot make any more moves, ie. the stones are in consecutive positions. When the game ends, what is the minimum and maximum number of moves that you could have made? Return the answer as an length 2 array: answer = [minimum_moves, maximum_moves] Input: [7,4,9] Output: [1,2]

class Solution { public: vector<int> numMovesStonesII(vector<int>& stones) { int size = stones.size(); if(size < 3) return {}; sort(stones.begin(), stones.end()); int minV = INT_MAX; int maxV = 0; int l = 0; for(int r = 0; r < size; r ++) { while(stones[r] - stones[l] >= size) l ++; int inplace = r - l + 1; if(inplace == size-1 && stones[r] - stones[l] + 1 == size-1) minV = min(minV, 2); else { minV = min(minV, size - inplace); } } int v1 = stones[size-2] - stones[0]; int v2 = stones[size-1] - stones[1]; maxV = max(v1 ,v2) - (size-2); return {minV, maxV}; } };

1053. Previous Permutation With One Swap Given an array A of positive integers (not necessarily distinct), return the lexicographically largest permutation that is smaller than A, that can be made with one swap (A swap exchanges the positions of two numbers A[i] and A[j]). If it cannot be done, then return the same array. Input: [3,2,1] Output: [3,1,2]

class Solution { public: vector<int> prevPermOpt1(vector<int>& A) { stack<int> s; int size = A.size(); int i = size-1; for(; i >= 0; i --) { if(!s.empty() && A[i] > A[s.top()]) break; if(!s.empty() && A[i] == A[s.top()]) s.pop(); s.push(i); } if(i < 0) return A; int ind; while(!s.empty() && A[i] > A[s.top()]) { ind = s.top(); s.pop(); } swap(A, i, ind); return A; } void swap(vector<int>& arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] =tmp; } };

985. Sum of Even Numbers After Queries We have an array A of integers, and an array queries of queries. For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index]. Then, the answer to the i-th query is the sum of the even values of A. (Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.) Return the answer to all queries. Your answer array should have answer[i] as the answer to the i-th query. Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]] Output: [8,6,2,4]

class Solution { public: vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries) { int size = queries.size(); vector<int> res; int sum = 0; for(auto& num: A) if(num % 2 == 0) sum += num; for(auto& pair: queries) { int val = pair[0]; int ind = pair[1]; int ori = A[ind]; if(ori % 2 == 0) { if(val % 2 == 0) sum += val; else sum -= ori; } else { if(val % 2 != 0) sum += (val + ori); } res.push_back(sum); A[ind] = ori +val; } return res; } };

1002. Find Common Characters Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer. You may return the answer in any order. Input: ["bella","label","roller"] Output: ["e","l","l"]

class Solution { public: vector<string> commonChars(vector<string>& A) { unordered_map<char,int> counts; for(auto& ch: A[0]) counts[ch] ++; for(int i = 1; i < A.size(); i ++ ) { unordered_map<char, int> tmp; for(auto& ch: A[i]) tmp[ch] ++; for(auto& [ch, cnt]: counts) counts[ch] = min(counts[ch], tmp[ch]); } vector<string> res; for(auto& [ch, cnt]: counts) { for(int i = 0; i< cnt; i ++) res.push_back(string(1, ch)); } return res; } };

1144. Decrease Elements To Make Array Zigzag Given an array nums of integers, a move consists of choosing any element and decreasing it by 1. An array A is a zigzag array if either: Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ... OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ... Return the minimum number of moves to transform the given array nums into a zigzag array. Input: nums = [1,2,3] Output: 2

if even index is larger, then we get min(arr[0], arr[2]) and decrease arr[1] to min-1..... if odd index is larger, then we first decrase arr[0], then get min(arr[1], arr[3]) and decrease arr[2] to min-1. class Solution { public: int movesToMakeZigzag(vector<int>& nums) { if(nums.size() < 2) return 0; int size = nums.size(); int v1 = 0; for(int i = 0; i < size; i += 2) { if(i + 1 >= size) continue; int minV = nums[i]; if(i +2 < size) minV = min(minV, nums[i+2]); if(nums[i+1] >= minV) v1 += (nums[i+1] - minV + 1); } int v2 = 0; if(nums[0] >= nums[1]) v2 += nums[0] - (nums[1] - 1); for(int i = 1; i < size; i += 2) { if(i+1 >= size) continue; int minV = nums[i]; if(i +2 < size) minV = min(minV, nums[i+2]); if(nums[i+1] >= minV) v2 += (nums[i+1] - minV + 1); } return min(v1, v2); } };

1035. Uncrossed Lines We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Input: A = [1,4,2], B = [1,2,4] Output: 2

use dp. class Solution { public: int maxUncrossedLines(vector<int>& A, vector<int>& B) { int m = A.size(); int n = B.size(); vector<vector<int>> dp(m+1, vector<int>(n+1)); for(int i = 1; i <= m; i ++) { for(int j = 1; j<= n; j ++) { if(A[i-1] == B[j-1]) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } return dp[m][n]; } };

1122. Relative Sort Array Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order. Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] Output: [2,2,2,1,4,3,3,9,6,7,19]

use indMap[i] = i - arr.size(). so index element has negative priority, others has 0. struct comparer { bool operator() (pair<int,int>& p1, pair<int,int>& p2) { return p1.second < p2.second ||(p1.second == p2.second && p1.first < p2.first); } }; class Solution { public: vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) { unordered_map<int, int> indMap; for(int i = 0; i < arr2.size(); i ++) indMap[arr2[i]] = i - arr2.size(); vector<pair<int,int>> arr; for(auto& num: arr1) { arr.push_back(pair(num, indMap[num])); } sort(arr.begin(), arr.end(), comparer() ); vector<int> res; for(auto& pair: arr) res.push_back(pair.first); return res; } };

1031. Maximum Sum of Two Non-Overlapping Subarrays Given an array A of non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays, which have lengths L and M. (For clarification, the L-length subarray could occur before or after the M-length subarray.) Formally, return the largest V for which V = (A[i] + A[i+1] + ... + A[i+L-1]) + (A[j] + A[j+1] + ... + A[j+M-1]) and either: 0 <= i < i + L - 1 < j < j + M - 1 < A.length, or 0 <= j < j + M - 1 < i < i + L - 1 < A.length. Input: A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2 Output: 20

use left[i] to record the max L sum until index i. use right[i] to record the max L sum from i. then we get M sum and add left[i-M] or right[i+1] class Solution { public: int maxSumTwoNoOverlap(vector<int>& A, int L, int M) { int size = A.size(); vector<int> left(size); int sum = 0; int maxV = 0; for(int i = 0; i < size; i ++) { sum += A[i]; if(i >= L) { sum -= A[i-L]; } maxV = max(maxV, sum); if(i >= L-1) left[i] = maxV; } vector<int> right(size); sum = 0; maxV = 0; for(int i = size-1; i >= 0; i --) { sum += A[i]; if(i + L < size) sum -= A[i+L]; maxV = max(maxV, sum); if(i + L - 1 < size) right[i] = maxV; } int res = 0; sum = 0; for(int i = 0 ; i< size; i ++) { sum += A[i]; if(i >= M) sum -= A[i-M]; int v1 = -1; int v2 = -1; if(i >= L + M - 1) v1 = sum + left[i-M]; if(i + L < size) v2 = sum + right[i +1]; res = max(res, max(v1, v2)); } return res; } };

1146. Snapshot Array Implement a SnapshotArray that supports the following interface: SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0. void set(index, val) sets the element at the given index to be equal to val. int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1. int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id Input: ["SnapshotArray","set","snap","set","get"] [[3],[0,5],[],[0,6],[0,0]] Output: [null,null,0,null,5]

use maps of maps. during get, if current index can't find snap_id, decrease snap_id and find. class SnapshotArray { private: unordered_map<int, unordered_map<int,int>> snaps; int id; public: SnapshotArray(int length) { id = 0; } void set(int index, int val) { snaps[index][id] = val; } int snap() { id ++; return id-1; } int get(int index, int snap_id) { while(snap_id > 0 && snaps[index].find(snap_id) == snaps[index].end()) { snap_id --; } return snaps[index][snap_id]; } }; /** * Your SnapshotArray object will be instantiated and called as such: * SnapshotArray* obj = new SnapshotArray(length); * obj->set(index,val); * int param_2 = obj->snap(); * int param_3 = obj->get(index,snap_id); */

1099. Two Sum Less Than K Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying this equation, return -1. Input: A = [34,23,1,24,75,33,54,8], K = 60 Output: 58

use set and lower_bound. class Solution { public: int twoSumLessThanK(vector<int>& A, int K) { int size = A.size(); set<int> nums; nums.insert(A[0]); int res = -1; for(int i = 1; i < size; i ++) { int num = A[i]; if(num >= K) continue; auto ite = nums.lower_bound(K - num); if(ite != nums.begin()) { --ite; res = max(res, num + *ite); } nums.insert(num); } return res; } };

1013. Partition Array Into Three Parts With Equal Sum Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums. Formally, we can partition the array if we can find indexes i+1 < j with (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1]) Input: [0,2,1,-6,6,-7,9,1,2,0,1] Output: true Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1

we get the average target, then check the sum. class Solution { public: bool canThreePartsEqualSum(vector<int>& A) { int sum = 0; for(int i = 0; i < A.size(); i ++) { sum += A[i]; } if(sum % 3 != 0) return false; int ave = sum / 3; sum = 0; int res = 0; for(auto& num: A) { sum += num; if(sum == ave) { res ++; sum = 0; } } return sum == 0 && res == 3; } };

1170. Compare Strings by Frequency of the Smallest Character Let's define a function f(s) over a non-empty string s, which calculates the frequency of the smallest character in s. For example, if s = "dcce" then f(s) = 2 because the smallest character is "c" and its frequency is 2. Now, given string arrays queries and words, return an integer array answer, where each answer[i] is the number of words such that f(queries[i]) < f(W), where W is a word in words. Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"] Output: [1,2]

we get the counts of words and prefix sums. class Solution { public: vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) { vector<int> counts(11); getCounts(words, counts); vector<int> sums(11); for(int i = 1; i <= 10; i ++) { sums[i] = sums[i-1] + counts[i]; } vector<int> res; for(int i = 0; i < queries.size(); i ++) { int cnt = count(queries[i]); int more = sums[10] - sums[cnt]; res.push_back(more); } return res; } void getCounts(vector<string>& arr, vector<int>& counts) { for(auto& str: arr) { int cnt = count(str); counts[cnt] ++; } } int count(string s) { map<char,int> countMap; for(auto& ch: s) countMap[ch] ++; return countMap.begin() ->second; } };

1007. Minimum Domino Rotations For Equal Row In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the i-th domino, so that A[i] and B[i] swap values. Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same. If it cannot be done, return -1. Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] Output: 2

we get the total count. the count >= half, is the target. class Solution { public: int minDominoRotations(vector<int>& A, vector<int>& B) { unordered_map<int,int> counts; int m = A.size(); for(auto& num: A) counts[num] ++; for(auto& num: B) counts[num] ++; int half = m; int target = -1; for(auto& [num, cnt]: counts) { if(cnt >= half) { target = num; break; } } if(target == -1) return -1; int v1 = 0; int v2 = 0; for(int i = 0; i < m; i ++) { if(A[i] != target && B[i] != target) return -1; else if(A[i] != target) v1 ++; else if(B[i] != target) v2 ++; else continue; } return min(v1, v2); } };

962. Maximum Width Ramp Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] <= A[j]. The width of such a ramp is j - i. Find the maximum width of a ramp in A. If one doesn't exist, return 0. Input: [6,0,8,2,1,5] Output: 4

we push the index val into pair and sort by increasing val. then keep the min index, and update the res. struct comparer { bool operator() (pair<int,int>& p1, pair<int,int>& p2) { return p1.second < p2.second || (p1.second == p2.second && p1.first < p2.first); } }; class Solution { public: int maxWidthRamp(vector<int>& A) { int size = A.size(); vector<pair<int,int> > arr; for(int i = 0 ;i < size; i ++) arr.push_back(pair(i, A[i])); sort(arr.begin(), arr.end(), comparer()); int res = 0; int minInd = INT_MAX; for(auto& pair: arr) { if(pair.first < minInd) minInd = pair.first; else { res = max(res, pair.first - minInd); } } return res; } };

1014. Best Sightseeing Pair Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i between them. The score of a pair (i < j) of sightseeing spots is (A[i] + A[j] + i - j) : the sum of the values of the sightseeing spots, minus the distance between them. Return the maximum score of a pair of sightseeing spots. Input: [8,1,5,2,6] Output: 11

we record left array as max arr[i] + i, and right array as max arr[i] - i. class Solution { public: int maxScoreSightseeingPair(vector<int>& A) { int size = A.size(); vector<int> left(size); left[0] = A[0]; for(int i =1; i < size; i ++) { left[i] = max(A[i] + i, left[i-1]); } vector<int> right(size); right[size-1] = A[size-1] - (size-1); for(int i = size-2; i >= 0; i --) { right[i] = max(A[i] - i, right[i+1]); } int res = 0; for(int i = 0; i+1 < size; i ++) { res = max(res, left[i] + right[i+1]); } return res; } };

1089. Duplicate Zeros Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place, do not return anything from your function. [8,4,5,0,0,0,0,7] [8,4,5,0,0,0,0,0]

we record the count of 0, and iterate from end to start. class Solution { public: void duplicateZeros(vector<int>& A) { int size = A.size(); int count = 0; for(auto& num: A) if(num == 0) count ++; for(int i = size-1; i >= 0; i --) { if(i + count >= size) { if(A[i] == 0) { if(i + count-1 == size-1) A[size-1] = 0; count --; } continue; } if(A[i] == 0) { A[i+count] = 0; A[i+count-1] = 0; count --; } else A[i+count] = A[i]; } } };

1157. Online Majority Element In Subarray Implementing the class MajorityChecker, which has the following API: MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr; int query(int left, int right, int threshold) has arguments such that: 0 <= left <= right < arr.length representing a subarray of arr; 2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists. MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]); majorityChecker.query(0,5,4); // returns 1 majorityChecker.query(0,3,3); // returns -1 majorityChecker.query(2,3,2); // returns 2

we record the counts[i]: until index i, the count of arr[i]. then use Boyer-Moor vote to get the majority candicate and get the real count. class MajorityChecker { private: vector<int> arr; vector<int> counts; public: MajorityChecker(vector<int>& arr) { this -> arr = arr; int size = arr.size(); counts = vector<int>(size); unordered_map<int,int> countMap; for(int i = 0; i < size; i ++) { countMap[arr[i]] ++; counts[i] = countMap[arr[i]]; } } int query(int left, int right, int threshold) { //Boyer-Moor vote int val = 0; int cnt = 0; for(int i = left; i <= right; i ++) { if(cnt == 0) { val = arr[i]; cnt = 1; } else if(arr[i] == val) cnt ++; else cnt --; } while(arr[left] != val) left ++; while(arr[right] != val) right --; int count = counts[right] - counts[left] + 1; return count >= threshold? val: -1; } }; /** * Your MajorityChecker object will be instantiated and called as such: * MajorityChecker* obj = new MajorityChecker(arr); * int param_1 = obj->query(left,right,threshold); */

978. Longest Turbulent Subarray A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if: For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even; OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd. That is, the subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray. Return the length of a maximum size turbulent subarray of A. Input: [9,4,2,10,7,8,8,1,9] Output: 5

we record the diff value as -1, 0 and 1. class Solution { public: int maxTurbulenceSize(vector<int>& A) { int size = A.size(); if(size < 2) return size; vector<int> diff; for(int i = 0; i +1 < size; i ++) { diff.push_back(A[i+1] - A[i] > 0? 1: (A[i+1] - A[i] == 0? 0: -1) ); } int res= 0; int start = 0; for(int i = 1; i + 1 <size; i++) { if(diff[i] * diff[i-1] < 0) continue; else { int len = i - start + 1; if(diff[i-1] == 0) len --; res = max(res, len); start = i; } } int len = size - start; if(diff[size-2] == 0) len --; res = max(res, len); return res; } };

974. Subarray Sums Divisible by K Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K. Input: A = [4,5,0,-2,-3,1], K = 5 Output: 7

we record the sum % k value. class Solution { public: int subarraysDivByK(vector<int>& A, int K) { int res = 0; int sum = 0; unordered_map<int, int> sums; sums[0] = 1; for(auto& num: A) { sum = ( (sum + num) % K + K) % K; res += sums[sum]; sums[sum] ++; } return res; } };

1169. Invalid Transactions A transaction is possibly invalid if: the amount exceeds $1000, or; if it occurs within (and including) 60 minutes of another transaction with the same name in a different city. Each transaction string transactions[i] consists of comma separated values representing the name, time (in minutes), amount, and city of the transaction. Given a list of transactions, return a list of transactions that are possibly invalid. You may return the answer in any order. Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"] Output: ["alice,20,800,mtv","alice,50,100,beijing"]

we split each transation into Tran struct and do O(n^2) iteration. struct Tran { string name; int time; int amount; string place; Tran() {}; Tran(string name, int time, int amount, string place):name(name),time(time), amount(amount), place(place) {}; }; class Solution { public: vector<string> invalidTransactions(vector<string>& arr) { vector<Tran> trans; unordered_set<int> inds; for(int i = 0; i < arr.size(); i ++) { string name; int time; int amount; string place; getInfo(arr[i], name, time, amount, place); trans.push_back(Tran(name, time, amount, place)); } int size = trans.size(); for(int i = 0; i < size; i ++) { if(trans[i].amount > 1000) { inds.insert(i); continue; } for(int j = 0; j < size; j ++) if(i != j) { if(trans[i].name == trans[j].name && abs(trans[i].time - trans[j].time) <= 60 && trans[i].place != trans[j].place) { inds.insert(i); inds.insert(j); } } } vector<string> res; for(auto& ind: inds) res.push_back(arr[ind]); return res; } void getInfo(string s, string& name, int& time, int& amount, string& place) { int pos = s.find(","); for(int i = 0; i < 3; i ++) { if(pos != -1) { string sub = s.substr(0, pos); if(i == 0) name = sub; else if(i == 1) time = stoi(sub); else if(i == 2) amount = stoi(sub); s.erase(0, pos+1); pos = s.find(","); } } place = s; } };

1010. Pairs of Songs With Total Durations Divisible by 60 In a list of songs, the i-th song has a duration of time[i] seconds. Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i < j with (time[i] + time[j]) % 60 == 0. Input: [30,20,150,100,40] Output: 3

we use count map to record the count of previous time. class Solution { public: int numPairsDivisibleBy60(vector<int>& time) { unordered_map<int,int> counts; int res = 0; for(auto& num: time) { num %= 60; int expected = num == 0? 0: 60 - num; res += counts[expected]; counts[num] ++; } return res; } };

969. Pancake Sorting Given an array A, we can perform a pancake flip: We choose some positive integer k <= A.length, then reverse the order of the first k elements of A. We want to perform zero or more pancake flips (doing them one after another in succession) to sort the array A. Return the k-values corresponding to a sequence of pancake flips that sort A. Any valid answer that sorts the array within 10 * A.length flips will be judged as correct. Input: [3,2,4,1] Output: [4,2,4,3]

we use indMap, get the next max value and flip to first position. then flip the first k value, so the next max goes to end. class Solution { public: vector<int> pancakeSort(vector<int>& A) { int size = A.size(); unordered_map<int,int> indMap; for(int i = 0; i < size; i++) indMap[A[i]] = i; vector<int> res; for(int i = size-1; i >= 1; i --) { if(A[i] != i + 1) { int ind = indMap[i+1]; if(ind != 0) { res.push_back(ind + 1); flip(A, indMap, 0, ind); } res.push_back(i+1); flip(A, indMap, 0, i); } } return res; } void flip(vector<int>& A, unordered_map<int,int>& indMap, int start, int end) { int i = start; int j = end; while(i <= j) { indMap[A[i]] = j; indMap[A[j]] = i; int tmp = A[i]; A[i] = A[j]; A[j] = tmp; i ++; j --; } } };

1128. Number of Equivalent Domino Pairs Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j]. Input: dominoes = [[1,2],[2,1],[3,4],[5,6]] Output: 1

we use minV*9 + maxV as key. class Solution { public: int numEquivDominoPairs(vector<vector<int>>& dominoes) { unordered_map<int, int> nums; for(auto& arr: dominoes) { int minV = min(arr[0], arr[1]); int maxV = max(arr[0], arr[1]); int val = minV * 9 + maxV; nums[val] ++; } int res = 0; for(auto&& [num, cnt]: nums) if(cnt > 1) res += (cnt-1) * cnt / 2; return res; } };


Set pelajaran terkait

Growth, Development, and Stages of Life

View Set

6.5.1 Creating and Altering Data Structures Quiz

View Set

Preeclampsia Simulation:Real Life RN Maternal Newborn 2.0

View Set