Leetcode1403. Minimum Subsequence in Non-Increasing Order
Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence.
If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array.
Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.
Example 1:
1 2 3
Input: nums = [4,3,10,9,8] Output: [10,9] Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included, however, the subsequence [10,9] has the maximum total sum of its elements.
classSolution { public: vector<int> minSubsequence(vector<int>& nums){ vector<int> res; sort(nums.begin(), nums.end()); int sum = 0; for(int i : nums) sum += i; sum /= 2; for(int i = nums.size()-1; i >= 0; i --) { if(sum < 0) break; sum -= nums[i]; res.push_back(nums[i]); } return res; } };
Leetcode1408. String Matching in an Array
Given an array of string words. Return all strings in words which is substring of another word in any order. String words[i] is substring of words[j], if can be obtained removing some characters to left and/or right side of words[j].
Example 1:
1 2 3 4
Input: words = ["mass","as","hero","superhero"] Output: ["as","hero"] Explanation: "as" is substring of "mass" and "hero" is substring of "superhero". ["hero","as"] is also a valid answer.
Example 2:
1 2 3
Input: words = ["leetcode","et","code"] Output: ["et","code"] Explanation: "et", "code" are substring of "leetcode".
找到字符串数组中哪些字符串是另一些字符串的子串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: staticboolcmp(string a, string b){ return a.length() < b.length(); } vector<string> stringMatching(vector<string>& words){ set<string> res; sort(words.begin(), words.end(), cmp); int len = words.size(); for(int i = 0; i < len; i ++) for(int j = i + 1; j < len; j ++) if(words[j].find(words[i]) != -1) res.insert(words[i]); returnvector<string>(res.begin(), res.end()); } };
Leetcode1413. Minimum Value to Get Positive Step by Step Sum
Given an array of integers nums, you start with an initial positive value startValue. In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1.
Example 1:
1 2 3 4 5 6 7 8 9 10
Input: nums = [-3,2,-3,4,2] Output: 5 Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1. step by step sum startValue = 4 | startValue = 5 | nums (4 -3 ) = 1 | (5 -3 ) = 2 | -3 (1 +2 ) = 3 | (2 +2 ) = 4 | 2 (3 -3 ) = 0 | (4 -3 ) = 1 | -3 (0 +4 ) = 4 | (1 +4 ) = 5 | 4 (4 +2 ) = 6 | (5 +2 ) = 7 | 2
Example 2:
1 2 3
Input: nums = [1,2] Output: 1 Explanation: Minimum start value should be positive.
classSolution { public: intminStartValue(vector<int>& nums){ int minn = 99999, sum = 0; for(int i = 0; i < nums.size(); i ++) { sum += nums[i]; minn = min(minn, sum); } if(minn < 0) returnabs(minn) + 1; return1; } };
Leetcode1417. Reformat The String
Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.
Return the reformatted string or return an empty string if it is impossible to reformat the string.
Example 1:
1 2 3
Input: s = "a0b1c2" Output: "0a1b2c" Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.
Example 2:
1 2 3
Input: s = "leetcode" Output: "" Explanation: "leetcode" has only characters so we cannot separate them by digits.
string reformat(string s){ string res; vector<char> a, b; for(int i = 0; i < s.length(); i ++) { if('0' <= s[i] && s[i] <= '9') a.push_back(s[i]); else b.push_back(s[i]); } int lena = a.size(), lenb = b.size(); int abss = lena - lenb; cout<<abss<<endl; if(abs(abss) > 1) return""; int k = 0; if(lena > lenb) { k = 0; for(char c : a) { s[k] = c; k += 2; } k = 1; for(char c : b) { s[k] = c; k += 2; } } else { k = 0; for(char c : b) { s[k] = c; k += 2; } k = 1; for(char c : a) { s[k] = c; k += 2; } } return s; } };
Leetcode1418. Display Table of Food Orders in a Restaurant
Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.
Return the restaurant’s “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.
Example 1:
1 2 3 4 5 6 7 8 9 10 11
Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]] Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] Explanation: The displaying table looks like: Table,Beef Burrito,Ceviche,Fried Chicken,Water 3 ,0 ,2 ,1 ,0 5 ,0 ,1 ,0 ,1 10 ,1 ,0 ,0 ,0 For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche". For the table 5: Carla orders "Water" and "Ceviche". For the table 10: Corina orders "Beef Burrito".
for(vector<string> a : orders) { if(find(res[0].begin(), res[0].end(), a[2]) == res[0].end()) res[0].push_back(a[2]); mp[stoi(a[1])][a[2]] ++; } sort(res[0].begin(), res[0].end()); for(auto it = mp.begin(); it != mp.end(); it ++) { for(string a : res[0]) if(it->second.find(a) == it->second.end()) it->second.insert(pair<string, int>(a, 0)); } res[0].insert(res[0].begin(), "Table"); for(auto it = mp.begin(); it != mp.end(); it ++) { vector<string> temp; temp.push_back(to_string(it->first)); for(auto itt = it->second.begin(); itt != it->second.end(); itt ++) { temp.push_back(to_string(itt->second)); } res.push_back(temp); } return res; } };
Leetcode1422. Maximum Score After Splitting a String
Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).
The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.
Example 1:
1 2 3 4 5 6 7 8 9
Input: s = "011101" Output: 5 Explanation: All possible ways of splitting s into two non-empty substrings are: left = "0" and right = "11101", score = 1 + 4 = 5 left = "01" and right = "1101", score = 1 + 3 = 4 left = "011" and right = "101", score = 1 + 2 = 3 left = "0111" and right = "01", score = 1 + 1 = 2 left = "01110" and right = "1", score = 2 + 1 = 3
Example 2:
1 2 3
Input: s = "00111" Output: 5 Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5
classSolution { public: intmaxScore(string s){ int left = 0, right = 0, res = 0; for(int i = 0; i < s.length(); i ++) if(s[i] == '1') right ++; for(int i = 0; i < s.length()-1; i ++) { if(s[i] == '1') { res = max(res, left + right -1); right --; } else { res = max(res, left + right + 1); left ++; } } return res; } };
Leetcode1424. Diagonal Traverse II
Given a list of lists of integers, nums, return all elements of nums in diagonal order as shown in the below images.
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
1 2 3
Input: nums = [10,2,-10,5,20], k = 2 Output: 37 Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
1 2 3
Input: nums = [-1,-2,-3], k = 1 Output: -1 Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
1 2 3
Input: nums = [10,-2,-10,-5,20], k = 2 Output: 23 Explanation: The subsequence is [10, -2, -5, 20].
classSolution { public: intconstrainedSubsetSum(vector<int>& a, int k){ // 是一个结合了滑动窗口最大值的dp // 使用滑动窗口计算最大值,再使用dp求最大值 int n = a.size(); deque<int> d; int ret = -10000; vector<int> f(n); // f[i] 是考虑前i个元素且选中第i个元素时构造的最大子序列和 for (int i = 0; i < n; i ++) { int l = i - k - 1; // 当前窗口的范围 if (!d.empty() && d.front() == l) d.pop_front(); // 先把上一个窗口的左端点踢出来 f[i] = a[i]; if (!d.empty()) f[i] = max(f[i], f[d.front()] + a[i]); while(!d.empty() && f[d.back()] <= f[i]) d.pop_back(); d.push_back(i); ret = max(ret, f[i]); } return ret; } };
Leetcode1431. Kids With the Greatest Number of Candies
Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has. For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.
Example 1:
1 2 3 4 5 6 7 8
Input: candies = [2,3,5,1,3], extraCandies = 3 Output: [true,true,true,false,true] Explanation: Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids. Kid 2 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. Kid 3 has 5 candies and this is already the greatest number of candies among the kids. Kid 4 has 1 candy and even if he or she receives all extra candies will only have 4 candies. Kid 5 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids.
classSolution { public: vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies){ vector<bool> res(candies.size(), false); int maxx = -1; for(int i = 0; i < candies.size(); i ++) if(maxx < candies[i]) maxx = candies[i]; for(int i = 0; i < candies.size(); i ++) if(candies[i] + extraCandies >= maxx) res[i] = true; return res; } };
Leetcode1436. Destination City
You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.
It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.
Example 1:
1 2 3
Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] Output: "Sao Paulo" Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo".
classSolution { public: string destCity(vector<vector<string>>& paths){ map<string, pair<int, int>> mp; for(int i = 0; i < paths.size(); i ++) { mp[paths[i][0]].first++; mp[paths[i][1]].second++; } for(auto it = mp.begin(); it != mp.end(); it ++) { if(it->second.first == 0 && it->second.second == 1) return it->first; } return""; } };
Leetcode1441. Build an Array With Stack Operations
Given an array target and an integer n. In each iteration, you will read a number from list = {1,2,3…, n}. Build the target array using the following operations:
Push: Read a new element from the beginning list, and push it in the array.
Pop: delete the last element of the array.
If the target array is already built, stop reading more elements. You are guaranteed that the target array is strictly increasing, only containing numbers between 1 to n inclusive.
Return the operations to build the target array. You are guaranteed that the answer is unique.
Example 1:
1 2 3 4 5 6
Input: target = [1,3], n = 3 Output: ["Push","Push","Pop","Push"] Explanation: Read number 1 and automatically push in the array -> [1] Read number 2 and automatically push in the array then Pop it -> [1] Read number 3 and automatically push in the array -> [1,3]
classSolution { public: intcountTriplets(vector<int>& arr){ int ret = 0; int n = arr.size(); vector<int> dp(n, 0); dp[0] = arr[0]; for (int i = 1; i < n; i ++) dp[i] = dp[i-1] ^ arr[i]; int res = 0; for (int i = 0; i < n; i ++) for (int j = i+1; j < n; j ++) { int tmp = i > 0 ? (dp[i-1] ^ dp[j]) : dp[j]; if (tmp == 0) res += (j - i); } return res; } };
Leetcode1446. Consecutive Characters
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character. Return the power of the string.
Example 1:
1 2 3
Input: s = "leetcode" Output: 2 Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
1 2 3
Input: s = "abbcccddddeeeeedcba" Output: 5 Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
classSolution { public: intmaxPower(string s){ int count = 1; char c = s[0]; int res = -1; for(int i = 1; i < s.length(); i ++) { if(c == s[i]) { count ++; } else { res = max(res, count); c = s[i]; count = 1; } } res = max(res, count); return res; } };
Leetcode1450. Number of Students Doing Homework at a Given Time
Given two integer arrays startTime and endTime and given an integer queryTime. The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].
Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.
Example 1:
1 2 3 4 5 6
Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4 Output: 1 Explanation: We have 3 students where: The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4. The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4. The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
简单题,无聊,找到在queryTime时写作业的人。
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intbusyStudent(vector<int>& startTime, vector<int>& endTime, int queryTime){ int res = 0; for(int i = 0; i < startTime.size(); i ++) { if(startTime[i] <= queryTime && queryTime <= endTime[i]) res ++; } return res; } };
Leetcode1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence
Given a sentence that consists of some words separated by a single space, and a searchWord. You have to check if searchWord is a prefix of any word in sentence. Return the index of the word in sentence where searchWord is a prefix of this word (1-indexed).
If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1. A prefix of a string S is any leading contiguous substring of S.
Example 1:
1 2 3
Input: sentence = "i love eating burger", searchWord = "burg" Output: 4 Explanation: "burg" is prefix of "burger" which is the 4th word in the sentence.
Example 2:
1 2 3
Input: sentence = "this problem is an easy problem", searchWord = "pro" Output: 2 Explanation: "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.
Example 3:
1 2 3
Input: sentence = "i am tired", searchWord = "you" Output: -1 Explanation: "you" is not a prefix of any word in the sentence.
Example 4:
1 2
Input: sentence = "i use triple pillow", searchWord = "pill" Output: 4
classSolution { public: intisPrefixOfWord(string sentence, string searchWord){ int n = int(sentence.length()); int n1 = int(searchWord.length()); int res = 0; int t = 0; for(int i = 0; i < n; i ++) { if(i == 0 || sentence[i - 1] == ' ') { res ++; if(sentence[i] == searchWord[0]) { if(n1 == 1) return res; for(int j = 1; j < n1; j ++) { i++; if(sentence[i] != searchWord[j]) { t = 0; break; } else t = 1; } if(t == 1) return res; } } } return-1; } };
Leetcode1460. Make Two Arrays Equal by Reversing Sub-arrays
Given two integer arrays of equal length target and arr. In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. Return True if you can make arr equal to target, or False otherwise.
Example 1:
1 2 3 4 5 6 7
Input: target = [1,2,3,4], arr = [2,4,1,3] Output: true Explanation: You can follow the next steps to convert arr to target: 1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3] 2- Reverse sub-array [4,2], arr becomes [1,2,4,3] 3- Reverse sub-array [4,3], arr becomes [1,2,3,4] There are multiple ways to convert arr to target, this is not the only way to do so.
Example 2:
1 2 3
Input: target = [7], arr = [7] Output: true Explanation: arr is equal to target without any reverses.
Example 3:
1 2
Input: target = [1,12], arr = [12,1] Output: true
判断一个数组能否通过翻转子串变成另一个数组,通过统计每个数字的个数判断。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: boolcanBeEqual(vector<int>& target, vector<int>& arr){ vector<int> res(1001, 0); for(int i = 0; i < arr.size(); i ++) res[arr[i]] ++; for(int i = 0; i < target.size(); i ++) { res[target[i]] --; if(res[target[i]] < 0) returnfalse; } returntrue; } };
Leetcode1464. Maximum Product of Two Elements in an Array
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).
Example 1:
1 2 3
Input: nums = [3,4,5,2] Output: 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.
Example 2:
1 2 3
Input: nums = [1,5,4,5] Output: 16 Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.
Given the array nums consisting of 2n elements in the form [x1,x2,…,xn,y1,y2,…,yn]. Return the array in the form [x1,y1,x2,y2,…,xn,yn].
Example 1:
1 2 3
Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7] Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
1 2
Input: nums = [1,2,3,4,4,3,2,1], n = 4 Output: [1,4,2,3,3,2,4,1]
转换数组。。。。
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: vector<int> shuffle(vector<int>& nums, int n){ vector<int> res; for(int i = 0; i < nums.size()/2; i ++) { res.push_back(nums[i]); res.push_back(nums[i+n]); } return res; } };
Leetcode1475. Final Prices With a Special Discount in a Shop
Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not receive any discount at all.
Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.
Example 1:
1 2 3 4 5 6 7
Input: prices = [8,4,6,2,3] Output: [4,2,4,2,3] Explanation: For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4. For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2. For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4. For items 3 and 4 you will not receive any discount at all.
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums.
Example 1:
1 2 3
Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
求前缀和
1 2 3 4 5 6 7 8 9
classSolution { public: vector<int> runningSum(vector<int>& nums){ for(int i = 1; i < nums.size(); i ++) { nums[i] = nums[i] + nums[i-1]; } return nums; } };
Leetcode1486. XOR Operation in an Array
Given an integer n and an integer start. Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length. Return the bitwise XOR of all elements of nums.
Example 1:
1 2 3 4
Input: n = 5, start = 0 Output: 8 Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8. Where "^" corresponds to bitwise XOR operator.
求异或和。
1 2 3 4 5 6 7 8 9
classSolution { public: intxorOperation(int n, int start){ int res = start; for(int i = 1; i < n; i ++) res = res ^ (start + i * 2); return res; } };
Leetcode1491. Average Salary Excluding the Minimum and Maximum Salary
Given an array of unique integers salary where salary[i] is the salary of the employee i. Return the average salary of employees excluding the minimum and maximum salary.
Example 1:
1 2 3 4
Input: salary = [4000,3000,1000,2000] Output: 2500.00000 Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively. Average salary excluding minimum and maximum salary is (2000+3000)/2= 2500
去掉最值求平均。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: doubleaverage(vector<int>& salary){ int minn = 1e7, maxx = -1; for(int i = 0; i < salary.size(); i ++) { if(salary[i] > maxx) maxx = salary[i]; if(salary[i] < minn) minn = salary[i]; } int sum = 0, count = 0; for(int i = 0; i < salary.size(); i ++) if(salary[i] != minn && salary[i] != maxx) { sum += salary[i]; count ++; } return (double)sum / count; } };
Leetcode1492. The kth Factor of n
Given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0. Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.
Example 1:
1 2 3
Input: n = 12, k = 3 Output: 3 Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.
Example 2:
1 2 3
Input: n = 7, k = 2 Output: 7 Explanation: Factors list is [1, 7], the 2nd factor is 7.
找一个数的第k个因子,简单。评测机不稳定,我提交了三次有两次是memory战胜100%。
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intkthFactor(int n, int k){ int res = 0; for(int i = 1; i <= n; i++){ if(n % i == 0 && --k == 0) return i; } return-1; } };
Leetcode1496. Path Crossing
Given a string path, where path[i] = ‘N’, ‘S’, ‘E’ or ‘W’, each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.
Return True if the path crosses itself at any point, that is, if at any time you are on a location you’ve previously visited. Return False otherwise.
Example 1:
1 2 3
Input: path = "NES" Output: false Explanation: Notice that the path doesn't cross any point more than once.