Math first 50 (2 - 413)

¡Supera tus tareas y exámenes ahora con Quizwiz!

7. Reverse Integer Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321

edge case to consider: 1. reverse val > INT_MAX or < INT_MIN; class Solution { public: int reverse(int x) { int res = 0; while(x != 0) { int val = x % 10; x /= 10; if(res > INT_MAX / 10 || (res == INT_MAX / 10 && val > 7)) return 0; if(res < INT_MIN / 10 || (res == INT_MIN / 10 && val < -8)) return 0; res = res * 10 + val; } return res; } };

168. Excel Sheet Column Title Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB

first, it's 26 decimal system, so we need to % 26 or / 26. need to be careful. There is no 0 in this system. class Solution { public: string convertToTitle(int n) { string res; while(n > 0) { int rem = n % 26; if(rem == 0) res = 'Z' + res; else res = char(rem - 1 + 'A') + res; n = (n - 1) / 26; } return res; } };

258. Add Digits Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. Example: Input: 38 Output: 2

1 use string to get each digit and add 2. keep adding highest digit to remain and if >= 10, continue; class Solution { public: int addDigits(int num) { while(num >= 10) { int ten = num / 10; int remain = num - ten * 10; num = ten + remain; } return num; } int addDigits1(int num) { //convert to string int res = 0; string s = to_string(num); while(s.length() > 1) { for(auto& ch: s) res += (ch - '0'); s = to_string(res); res = 0; } return stoi(s); } };

43. Multiply Strings Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Input: num1 = "123", num2 = "456" Output: "56088"

1 use each digit of num2 to multiply num1 and add. 2. multiply every two digit of num1 and num2 and handle carry later. class Solution { private: int len1; int len2; public: string multiply(string num1, string num2) { if(num1 == "0" || num2 == "0") return "0"; len1 = num1.length(); len2 = num2.length(); reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); vector<int> arr(len1 + len2); for(int i = 0; i < len1; i ++) { for(int j = 0; j < len2; j ++) { arr[i+j] += (num1[i] - '0') * (num2[j] - '0'); } } cout <<" -- "<<endl; int carry = 0; for(int i = 0; i < len1 + len2; i ++) { int val = arr[i] + carry; arr[i] = val % 10; carry = val / 10; } while(arr.size() > 0 && arr.back() == 0) arr.pop_back(); string res = ""; for(int i = arr.size() - 1; i >= 0; i --) res += arr[i] + '0'; return res; } string multiply1(string num1, string num2) { //use each digit of num2 to multiply num1 and add reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); len1 = num1.length(); len2 = num2.length(); if(len1 == 0 || len2 == 0) return ""; if(num1 == "0" || num2 == "0") return "0"; vector<string> prod; for(int i = 0; i < len2; i ++) { string res = mul(num1, num2[i] - '0'); res.insert(res.begin(), i, '0'); prod.push_back(res); } string ans = prod[0]; for(int i = 1; i < len2; i ++) { ans = add(ans, prod[i]); } reverse(ans.begin(), ans.end()); return ans; } string mul(string s, int num) { int flag = 0; string res = ""; for(int i = 0; i < s.length(); i ++) { int val = num * (s[i] - '0') + flag; res += (val % 10) + '0'; flag = val / 10; } if(flag > 0) res += flag + '0'; return res; } string add(string s1, string s2) { int flag = 0; int l1 = s1.length(); int l2= s2.length(); int i = 0; int j = 0; string res = ""; while(i < l1 || j < l2) { int val = i >= l1? 0: s1[i] - '0'; val += (j >= l2? 0: s2[j] - '0') + flag; res += (val % 10) + '0'; flag = val / 10; i ++; j ++; } if(flag > 0) res += flag + '0'; return res; } };

172. Factorial Trailing Zeroes Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0

The key is to get the number of 5. class Solution { public: int trailingZeroes(int n) { long factor = 5; int res = 0; while(n >= factor) { res += n / factor; factor *= 5; } return res; } };

319. Bulb Switcher There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds. Input: 3 Output: 1 Explanation: At first, the three bulbs are [off, off, off]. After first round, the three bulbs are [on, on, on]. After second round, the three bulbs are [on, off, on]. After third round, the three bulbs are [on, off, off].

after going deeper to understand this problem, if one number n has even factors, it will be closed . Only when it has odd factors, it will remain open. class Solution { public: int bulbSwitch(int n) { return sqrt(n); } };

9. Palindrome Number Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

class Solution { public: bool isPalindrome(int x) { if(x < 0) return false; vector<int> arr; while(x > 0) { arr.push_back(x % 10); x /= 10; } int i = 0; int j = arr.size() - 1; while(i <= j ) { if(arr[i ++] != arr[j --]) return false; } return true; } };

231. Power of Two Given an integer, write a function to determine if it is a power of two.

class Solution { public: bool isPowerOfTwo(int n) { if(n <= 0) return false; bitset<32> bits(n); return bits.count() == 1; } };

8. String to Integer (atoi) The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

edge case: 1. > INT_MAX or < INT_MIN; 2. sign ( +, -) class Solution { public: int myAtoi(string str) { while(str[0] == ' ') str.erase(0, 1); int flag = 1; long res = 0; int len = str.length(); for(int i = 0; i < len; i ++) { if(str[i] == '-' && i == 0) flag = 0; else if(str[i] == '+' && i == 0) flag = 1; else if(isdigit(str[i])) { while(i < len && isdigit(str[i])) { res = res * 10 + str[i] - '0'; if( flag && res > INT_MAX ) return INT_MAX; if( !flag && -res < INT_MIN) return INT_MIN; i ++; } break; } else break; } return flag? res: -res; } };

29. Divide Two Integers Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. Return the quotient after dividing dividend by divisor. The integer division should truncate toward zero. Example 1: Input: dividend = 10, divisor = 3 Output: 3

edge case: INT_MIN / -1. class Solution { public: int divide(int dividend, int divisor) { bool nonNegative = (dividend >= 0) ^ (divisor > 0) == 0; long v1 = labs(dividend); long v2 = labs(divisor); if(v1 < v2) return 0; long res = 0; while(v1 >= v2) { int i = 0; while( (v2 << i) <= v1) i ++; i --; res += (long(1) << i); v1 -= (v2 << i); } if( (nonNegative && res > INT_MAX) ||(!nonNegative && -res < INT_MIN) ) return INT_MAX; return nonNegative? res: -res; } };

313. Super Ugly Number Write a program to find the nth super ugly number. Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. Example: Input: n = 12, primes = [2,7,13,19] Output: 32 Explanation: [1,2,4,7,8,13,14,16,19,26,28,32]

same as finding ugly number. We record the prime factor and the last index when this factor is used. class Solution { public: int nthSuperUglyNumber(int n, vector<int>& primes) { int size = primes.size(); vector< pair<int,int> > factors; for(int i = 0; i < size; i ++) { factors.push_back( pair(primes[i], 0) ); } if(n == 1) return 1; vector<int> arr(n); arr[0] = 1; for(int i = 1; i < n; i ++) { int minVal = factors[0].first * arr[factors[0].second]; for(int j = 1; j < size; j ++) { minVal = min(minVal, factors[j].first * arr[factors[j].second]); } arr[i] = minVal; for(int j = 0; j < size; j ++) { if(minVal == factors[j].first * arr[factors[j].second]) factors[j].second ++; } } return arr[n-1]; } };

233. Number of Digit One Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. Example: Input: 13 Output: 6

the result contains three parts: for example: 225. when highest bit is 0xx, 1xx, we have 2 * arr[2] counts. when highest bit is 1xx, we have another 100 counts. when highest bit is 2xx, we find out how 25 contains how many 1s. class Solution { public: int countDigitOne(int n) { if(n <= 0) return 0; string s = to_string(n); int len = s.length(); vector<int> arr(len); getArr(n, arr); int res = 0; for(int i = 0; i < len; i ++) { if(s[i] == '0') continue; int base = pow(10, len - i - 1); int factor = n / base; int remain = n % base; int count = s[i] > '1'? base: (remain +1); res += factor * arr[len - i -1] + count; n = remain; } return res; } void getArr(int n, vector<int>& arr) { arr[0] = 0; for(int i = 1; i < arr.size(); i ++) { arr[i] = 10 * arr[i-1] + pow(10, i - 1); } } };

357. Count Numbers with Unique Digits Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n. Example: Input: 2 Output: 91 Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99

three case: 1. n == 0: ans = 1 2. n == 1: ans = 10 3. n >= 2: n = 2: counts = 9 * 9, n = 3: 9 * 9 * 8.... class Solution { public: // if n == 1, we can have 0...9 // if n = 2, we have 9 * 9, n == 3: 9 *9 * 8.... // so we add up n >= 2 and add 10 at last int countNumbersWithUniqueDigits(int n) { if(n == 0) return 1; if(n == 1) return 10; int res = 0; for(int i = 2; i <= n; i ++) { int val = 1; for(int j = 0, options = 9; j < i - 1 && options >= 0; j ++, options --) { val *= options; } res += val * 9; } res += 10; return res; } };

367. Valid Perfect Square Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Output: true

use binary search. class Solution { public: bool isPerfectSquare(int num) { int l = 1; int r = num; while(l <= r) { long mid = l + (r - l) / 2; long prod = mid * mid; if(prod == num) return true; else if(prod < num) l = mid + 1; else r = mid - 1; } return false; } };

224. Basic Calculator Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . Input: "(1+(4+5+2)-3)+(6+8)" Output: 23

use operator and num stacks. class Solution { private: stack<int> s; stack<char> opS; public: int calculate(string str) { int len = str.length(); for(int i = 0; i < len; i ++) { if(isdigit(str[i])) { int num = 0; while(i < len && isdigit(str[i])) { num = num * 10 - '0' + str[i]; i ++; } i --; s.push(num); } else if(str[i] == '(') { opS.push(str[i]); } else if(str[i] == '+' || str[i] == '-') { while(!opS.empty() && opS.top() != '(') { calc(); } opS.push(str[i]); } else if(str[i] == ')') { while(opS.top() != '(') { calc(); } opS.pop(); } } while(! opS.empty()) { calc(); } return s.top(); } void calc() { int v1 = s.top(); s.pop(); int v2 = s.top(); s.pop(); char op = opS.top(); opS.pop(); int val = op == '+'? v1 + v2: v2 - v1; s.push(val); } };

372. Super Pow Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. Input: a = 2, b = [1,0] Output: 1024

use recursion to calc first size-1 array result. use pow(result, 10) * pow(a, b). class Solution { public: int superPow(int a, vector<int>& b) { a %= 1337; int size = b.size(); if(size == 0) return 1; vector<int> left(b.begin(), b.begin() + size - 1); int newBase = superPow(a, left); int res = calc(newBase, 10) * calc(a, b.back()) % 1337; return res; } int calc(int num, int val) { long res = 1; while(val > 0) { if(val % 2 == 1) { res = res * num % 1337; } val /= 2; num = num * num % 1337; } return res; } };

60. Permutation Sequence The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence.

we can get array to record how many sequences can be formed using n nums, and use k divide the nums to get index. class Solution { private: vector<int> arr; public: string getPermutation(int n, int k) { arr = vector<int>(n); getArr(n); string res = ""; vector<int> nums; for(int i = 1; i<= n; i ++) nums.push_back(i); for(int i = n-1; i >= 0; i --) { int ind = (k - 1) / arr[i]; k -= ind * arr[i]; res += nums[ind] + '0'; nums.erase(nums.begin() + ind); } return res; } void getArr(int n) { arr[0] = 1; for(int i = 1; i < n; i ++) { arr[i] = arr[i-1] * i; } } };

12. Integer to Roman I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900.

we use array of array to store the conversion. use helper function to do the map. class Solution { private: vector<vector<char> > chars = { {'I', 'V'}, {'X', 'L'}, {'C', 'D'}, {'M'} }; vector<int> digits; public: string intToRoman(int num) { while(num > 0) { digits.push_back(num % 10); num /= 10; } return solve(); } string solve() { int size = digits.size(); string res = ""; for(int i = size-1; i >= 0; i --) { int val = digits[i]; if(val == 4) { res += chars[i][0]; res += chars[i][1]; } else if(val == 9) { res += chars[i][0]; res += chars[i + 1][0]; } else if(val < 4) { for(int j = 0; j < val; j ++) { res += chars[i][0]; } } else { res += chars[i][1]; for(int j = 0; j < val - 5; j ++) { res += chars[i][0]; } } } return res; } };

360. Sort Transformed Array Given a sorted array of integers nums and integer values a, b and c. Apply a quadratic function of the form f(x) = ax2 + bx + c to each element x in the array. The returned array must be in sorted order. Input: nums = [-4,-2,2,4], a = 1, b = 3, c = 5 Output: [3,9,15,33]

we use two pointers left and right, there are 4 cases: 1. a > 0: edge values are always larger, start from size-1, keep decreasing res index. 2. a < 0: edge values are always smaller, start from 0, keep increasing index. 3. a==0, b < 0: store larger values first, start form size-1, decreasing 4. a== 0, b >= 0: store smaller values first, start from 0, increasing class Solution { public: vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) { int size = nums.size(); if(size == 0) return {}; int l = 0; int r = size - 1; int dir, k; if(a < 0 || (a == 0 && b >= 0)) { //get smaller end values and store in res dir = 1; k = 0; } else if(a > 0 || (a == 0 && b < 0)) { //get larger end values and store in res dir = -1; k = size - 1; } int v1 = getVal(a, b, c, nums[l]); int v2 = getVal(a, b, c, nums[r]); vector<int> res(size); while(l <= r){ if( (dir < 0 && v1 >= v2) || (dir > 0 && v1 <= v2) ) { res[k] = v1; l ++; if(l < size) v1 = getVal(a, b, c, nums[l]); } else { res[k] = v2; r --; if( r >= 0) v2 = getVal(a, b, c, nums[r]); } k += dir; } return res; } int getVal(int a, int b, int c, int val) { return a * val * val + b * val + c; } };

247. Strobogrammatic Number II A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. Example: Input: n = 2 Output: ["11","69","88","96"]

1. according to n % 2 == 1 or 0, we can get the mid chars. 2. iterate through the map, append char and its map to left and right side. class Solution { private: map<char, char> pairs = { {'0','0'}, {'1','1'}, {'6','9'}, {'8','8'}, {'9','6'} }; public: vector<string> findStrobogrammatic(int n) { vector<string> res = {""}; if(n % 2 == 1) res = {"0", "1", "8"}; int half = n / 2; vector<string> tmp; for(int i = 0; i < half; i ++) { for(auto& s: res) { for(auto& [ch, ch1]: pairs) { if(i ==half-1 && ch == '0') continue; string ss = ch + s + pairs[ch]; tmp.push_back(ss); } } res = tmp; tmp.clear(); } return res; } };

65. Valid Number Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number: Numbers 0-9 Exponent - "e" Positive/negative sign - "+"/"-" Decimal point - "."

1. trim string 2. check int (no char other than digit) 3. check float (at most one empty and both int) 4. check scientific (both non empty and left side int or float, right side int) class Solution { //https://leetcode.com/problems/valid-number/discuss/318369/C%2B%2B-modular-easy-to-understand public: bool isNumber(string s) { trim(s); if(s.length() != 0 && (s[0] == '-' || s[0] == '+')) s = s.substr(1); if(s.length() == 0) return false; return isInt(s) || isFloat(s) || isScientific(s); } bool isScientific(string s) { if(s.find("e") == string::npos) return false; int pos = s.find("e"); string left = s.substr(0, pos); string right = s.substr(pos + 1); if(!right.empty() && (right[0] == '+' || right[0] == '-') ) right = right.substr(1); if(left.empty() || right.empty()) return false; return (isFloat(left) || isInt(left)) && isInt(right); } bool isFloat(string s) { if(s.find(".") == string::npos) return false; int pos = s.find("."); string left = s.substr(0, pos); string right = s.substr(pos + 1); if(left.empty() && right.empty()) return false; if((left.empty() || isInt(left)) && (right.empty() || isInt(right))) return true; return false; } bool isInt(string s) { if(s.find_first_not_of("0123456789") == string::npos) return true; return false; } void trim(string& s) { int pos1 = s.find_first_not_of(' '); int pos2 = s.find_last_not_of(' '); if(pos1 == -1 || pos2 == -1) s = ""; else s = s.substr(pos1, pos2 - pos1 + 1); } };

268. Missing Number Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1: Input: [3,0,1] Output: 2

1. use array to mark used number to find missing one. 2. use bit xor. get xor of all nums 0...n, and get xor of vals nums[0], ... nums[size-1]; and result is xor of these two. class Solution { //https://leetcode.com/problems/missing-number/discuss/328715/Java-Bit-Manipulation-Solution-Beating-100-Solution public: int missingNumber(vector<int>& nums) { int size = nums.size(); int num = 0; int val = 0; for(int i = 0; i< size; i ++) { num ^= (i +1); val ^= (nums[i]); } return num ^ val; } int missingNumber1(vector<int>& nums) { //use array int size = nums.size(); vector<bool> arr(size + 1, false); for(auto& num: nums) arr[num] = true; for(int i = 0; i <= size; i ++) if(! arr[i]) return i; return -1; } };

273. Integer to English Words Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1. Input: 1234567891 Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

1. use map to store the units: thousand...Billion 2. use map to store 10 - 19.... 90, special nums class Solution { private: unordered_map<int, string> units = { {9, " Billion"}, {6, " Million"}, {3, " Thousand"}, {0, ""} }; unordered_map<int, string> strMap = { {0, "Zero"}, {1, "One"}, {2, "Two"}, {3, "Three"}, {4, "Four"}, {5, "Five"}, {6, "Six"}, {7, "Seven"}, {8, "Eight"}, {9, "Nine"} }; unordered_map<int, string> tenMap = { {10, "Ten"}, {11, "Eleven"}, {12, "Twelve"}, {13, "Thirteen"}, {14, "Fourteen"}, {15, "Fifteen"}, {16, "Sixteen"}, {17, "Seventeen"}, {18, "Eighteen"}, {19, "Nineteen"}, {2, "Twenty"}, {3, "Thirty"}, {4, "Forty"}, {5, "Fifty"}, {6, "Sixty"}, {7, "Seventy"}, {8, "Eighty"}, {9, "Ninety"} }; public: string numberToWords(int num) { if(num == 0) return "Zero"; int count = 9; string res; while(count >= 0) { int power = pow(10, count); if(num >= power) { res += getStr(num / power) + units[count] + (num % power == 0? "": " "); num %= power; } count -= 3; } return res; } string getStr(int num) { string res; if(num >= 100) { int val = num / 100; num %= 100; res += strMap[val] + " Hundred" + (num == 0? "": " "); } if(num / 10 == 1) res += tenMap[num]; else if(num / 10 > 1) { int val = num / 10; num %= 10; res += tenMap[val] + (num == 0? "": " "); } if(num != 0) res += strMap[num]; return res; } };

223. Rectangle Area Find the total area covered by two rectilinear rectangles in a 2D plane.

area1 + area2 - overlapping class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { long maxX = max(A, E); long minX = min(C, G); long maxY = max(B, F); long minY = min(D, H); long width = minX - maxX < 0? 0: (minX - maxX); long height = minY - maxY < 0? 0: (minY - maxY); long area1 = (C - A) * (D - B); long area2 = (G - E) * (H - F); return area1 + area2 - width * height; } };

69. Sqrt(x) Implement int sqrt(int x).

binary search. class Solution { public: int mySqrt(int x) { long l = 0; long r = x; while(l <= r) { long mid = l + (r - l) / 2; long val = mid * mid; if(val == x) return mid; else if(val < x) l = mid + 1; else r = mid -1; } return l - 1; } };

335. Self Crossing You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west, x[2] metres to the south, x[3] metres to the east and so on. In other words, after each move your direction changes counter-clockwise. ┌───┐ │ │ └───┼──> │ Input: [2,1,1,2] Output: true

calm first! there are three case of crossing. 1. 4 edges, 3 >= 1 && 2 >= 0 2. 5 edges, 3 == 1 && 4 + 0 >= 2; 3. 6 edges, 3 > 1 && 4 + 0 >= 2 && 4 <= 2 && 1 + 5 <= 3 class Solution { public: bool isSelfCrossing(vector<int>& x) { int size = x.size(); for(int i = 0; i < size; i ++) { if(i +3 < size && ( x[i] >= x[i+2] && x[i+3] >= x[i+1] )) return true; if( i + 4 < size && x[i+1] == x[i+3] && x[i + 2] <= x[i] + x[i + 4] ) return true; if(i + 5 < size && ( x[i+3] > x[i+1] && x[i] + x[i+4] >= x[i+2] && x[i+1] + x[i+5] >= x[i+3] && x[i+4] <= x[i+2]) ) return true; } return false; } };

50. Pow(x, n) Implement pow(x, n), which calculates x raised to the power n (xn). Example 1: Input: 2.00000, 10 Output: 1024.00000

can not use func. keep half the power and multiply the x. class Solution { public: double myPow(double x, int n) { long N = n; if(n < 0) { x = 1.0 / x; N = labs(n); } double res = 1.0; for(; N > 0; N /= 2) { if(N % 2 == 1) res *= x; x *= x; } return res; } };

171. Excel Sheet Column Number Given a column title as appear in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28

class Solution { public: int titleToNumber(string s) { long res = 0; for(auto& ch: s) { res = res * 26 + ch - 'A' +1; } return res; } };

67. Add Binary Input: a = "11", b = "1" Output: "100"

class Solution { public: string addBinary(string a, string b) { int m = a.length(); int n = b.length(); int flag = 0; string res; int i = m - 1; int j = n - 1; while( i >= 0 || j >= 0) { int val = i >= 0? a[i] - '0': 0; val += (j >= 0? b[j] - '0': 0) + flag; res = to_string(val % 2) + res; flag = val / 2; i --; j --; } if(flag > 0) res = to_string(flag) + res; return res; } };

326. Power of Three Given an integer, write a function to determine if it is a power of three. Example 1: Input: 27 Output: true

edge case: 1: num 1 class Solution { public: bool isPowerOfThree(int n) { if(n <= 0 ) return false; if(n == 1) return true; if(n % 3 != 0) return false; long factor = 3; while(n > factor) { factor *= factor; } if(n == factor) return true; factor = sqrt(factor); if(n % factor != 0) return false; return isPowerOfThree(n / factor); } };

397. Integer Replacement Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If n is odd, you can replace n with either n + 1 or n - 1. 8 -> 4 -> 2 -> 1

if n is even, -> n/ 2; if n is odd and(n + 1) % 4 == 0, plus, else minus class Solution { public: int integerReplacement(int n) { if(n == 1) return 0; if(n == 3) return 2; if(n == INT_MAX) return 32; if(n % 2 == 0) { n >>= 1; return 1 + integerReplacement(n); } else { if((n + 1) % 4 == 0) { return 1 + integerReplacement(n + 1); } else return 1 + integerReplacement(n-1); } return -1; } };

365. Water and Jug Problem You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs. If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end. Input: x = 3, y = 5, z = 4 Output: True

if z % gcd(x, y) == 0, can. class Solution { public: bool canMeasureWater(int x, int y, int z) { if(x == 0 && y == 0) return z == 0; if(x == 0) return z % y == 0; if(y == 0 ) return z % x == 0; if(z > x + y) return false; return (z % x == 0 || z % y == 0 || z % gcd(x, y) == 0); } int gcd(int v1, int v2) { if(v1 == 0) return v2; return gcd(v2 % v1, v1); } };

263. Ugly Number Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

keep divide 2, ,3,5 until can't class Solution { public: bool isUgly(int num) { if(num == 0) return false; // set<int, greater<int>> factors = {2, 3, 5}; // for(auto& num: factors) // for(auto& num1: factors) // factors.insert(num * num1); // for(auto& factor: factors) { // while(num % factor == 0) { // num /= factor; // } // } while(num % 2 == 0) num /= 2; while(num % 3 == 0) num /= 3; while(num % 5 == 0) num /= 5; return num == 1; } };

400. Nth Digit Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... Input: 11 Output: 0

keep track of the digits for len 1, len 2.... class Solution { public: int findNthDigit(int n) { int digit = 1; long count = 9; while(n > count * digit) { n -= count*digit; count *= 10; digit ++; } int val = pow(10, digit - 1) + (n - 1) / digit; string s = to_string(val); int ind = (n - 1) % digit; return s[ind] - '0'; } };

296. Best Meeting Point A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|. Example: Input: 1 - 0 - 0 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0 Output: 6

key: meet at the middle x and middle y point between these persons. class Solution { public: int minTotalDistance(vector<vector<int>>& grid) { int rows = grid.size(); if(rows == 0) return 0; int cols = grid[0].size(); vector<int> xs; vector<int> ys; vector<vector<int>> ps; for(int r = 0; r < rows; r ++) { for(int c = 0; c < cols; c ++) if(grid[r][c] == 1) { xs.push_back(r); ys.push_back(c); ps.push_back( {r, c} ); } } sort(xs.begin(), xs.end()); sort(ys.begin(), ys.end()); int size = xs.size(); if(size == 0) return 0; int mid = (size-1) / 2; vector<vector<int>> mids = { {xs[mid], ys[mid]} }; if(size % 2 == 0) mids.push_back( {xs[mid+1], ys[mid+1]} ); int res = INT_MAX; for(auto& pos: mids) { int sum = 0; for(auto& p: ps) { sum += abs(p[0] - pos[0]) + abs(p[1] - pos[1]); } res = min(res, sum); } return res; } };

279. Perfect Squares Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4.

we collect all the sqare values and put into array. use recursion to get the min num. class Solution { private: vector<int> arr; int res = INT_MAX; public: int numSquares(int n) { for(int i = int(sqrt(n)); i >= 1; i --) { arr.push_back(i * i); } solve(n, 0); return res; } void solve(int num, int count) { if(count >= res) return; if(num < 0) return; if(num == 0) { if(count < res) res = count; return; } for(auto& val: arr) { if(val <= num) { int tmp = num / val; solve(num - val * tmp, count + tmp); } } } };

248. Strobogrammatic Number III Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high. Example: Input: low = "50", high = "100" Output: 3

we get the center, and expand the string. class Solution { private: map<string, string> pairs = {{"0", "0"}, {"1", "1"}, {"6", "9"}, {"8", "8"}, {"9", "6"}}; int count = 0; int m; int n; public: int strobogrammaticInRange(string low, string high) { vector<string> centers = {"", "0", "1", "8"}; m = low.length(); n = high.length(); for(auto& center: centers) { if(isLarger(center, low, high)) break; getResult(center, low, high); } return count; } void getResult(string s, string low, string high) { for(auto& [s1, s2]: pairs) { string ss = s1 + s + s2; if(isLarger(ss, low, high)) return; getResult(ss, low, high); } } bool isLarger(string s, string low, string high) { int len = s.length(); if(len > n || (len == n && s > high)) return true; if(len > m || (len == m && s >= low)) { if(len == 1 || s[0] != '0') count ++; } return false; } };

413. Arithmetic Slices A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, these are arithmetic sequence: 1, 3, 5, 7, 9 A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N. A slice (P, Q) of array A is called arithmetic if the sequence: A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q. A = [1, 2, 3, 4] return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.

we keep track the previous diff and count. if current diff is different, add to count. class Solution { public: int numberOfArithmeticSlices(vector<int>& A) { int size = A.size(); if(size < 3) return 0; vector<int> arr(size, 1); int diff = INT_MAX; int count = 1; int res = 0; for(int i = 1; i < size; i ++) { int val = A[i] - A[i-1]; if(val == diff) count ++; else { if(count >= 3) res += (count - 1) * (count - 2) / 2; count = 2; diff = val; } } if(count >= 3) res += (count - 1) * (count - 2) / 2; return res; } };

13. Roman to Integer I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900.

we need to store the priority and the mapped value. class Solution { private: unordered_map<char, pair<int,int>> charMap; public: int romanToInt(string s) { buildMap(); int res = 0; int len = s.length(); for(int i = 0; i < len; i++) { if(i + 1 < len && charMap[s[i]].first < charMap[s[i+1]].first) { res += charMap[s[i+1]].second - charMap[s[i]].second; i ++; } else res += charMap[s[i]].second; } return res; } void buildMap() { int prio = 0; charMap['I'] = pair(prio ++, 1); charMap['V'] = pair(prio ++, 5); charMap['X'] = pair(prio ++, 10); charMap['L'] = pair(prio ++, 50); charMap['C'] = pair(prio ++, 100); charMap['D'] = pair(prio ++, 500); charMap['M'] = pair(prio ++, 1000); } };

396. Rotate Function Given an array of integers A and let n to be its length. Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow: F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1] A = [4, 3, 2, 6] F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26

we observe and get the regulation during operation. Every time rotation happens, last element moves to first. sum - lastElement added, (size-1) * lastElement minus. class Solution { public: int maxRotateFunction(vector<int>& A) { int size = A.size(); if(size == 0) return 0; long sum = 0; for(auto& num: A) sum += num; int res = 0; for(int i = 0; i < size; i ++) { res += i * A[i]; } int val = res; for(int i = size -1; i >= 0; i --) { val = val + (sum - A[i]) - (size - 1) * A[i]; res = max(res, val); } return res; } };

368. Largest Divisible Subset Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. Input: [1,2,4,8] Output: [1,2,4,8]

we sort array. then keep track the len for current index. class Solution { public: vector<int> largestDivisibleSubset(vector<int>& nums) { int size = nums.size(); if(size == 0) return {}; vector<int> counts(size, 1); vector<int> prev(size, -1); sort(nums.begin(), nums.end()); int res = 1; int ind = 0; for(int i = 1; i < size; i ++) { int maxCount = 1; int val = nums[i]; for(int j = 0; j < i; j ++) { if(nums[i] % nums[j] == 0 && counts[j] + 1 > maxCount) { maxCount = counts[j] + 1; prev[i] = j; } } counts[i] = maxCount; if(maxCount > res) { res = maxCount; ind = i; } } vector<int> ans; while(ind != -1) { ans.insert(ans.begin(), nums[ind]); ind = prev[ind]; } return ans; } };

343. Integer Break Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. Input: 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.

we use dp. calc and compare i * (n-i), i * arr[n-i] arrr[i] * (n - i) arr[i] * (n - i) class Solution { public: int integerBreak(int n) { vector<int> arr(n + 1); arr[1] = arr[2] = 1; for(int i = 3; i <= n; i ++) { int maxVal = 0; for(int l = 1; l <= (i + 1) / 2; l ++) { int r = i - l; maxVal = max(maxVal, l * r); maxVal = max(maxVal, l * (arr[r])); maxVal = max(maxVal, arr[l] * r); maxVal = max(maxVal, arr[l] * arr[r]); } arr[i] = maxVal; } return arr[n]; } };

264. Ugly Number II Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. Example: Input: n = 10 Output: 12 Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

when we already got nums with len k, with last 2 multiply nums[i], last 3 multiply nums[j], ... we record the index. class Solution { public: int nthUglyNumber(int n) { if(n == 1) return 1; vector<int> res(n); res[0] = 1; vector<pair<int,int>> factors; factors.push_back(pair(2, 0)); factors.push_back(pair(3, 0)); factors.push_back(pair(5, 0)); for(int i = 1; i < n; i ++) { int minVal = factors[0].first * res[factors[0].second]; for(int j = 1; j < 3; j ++) minVal = min(minVal, factors[j].first * res[factors[j].second]); res[i] = minVal; for(int j = 0; j < 3; j ++) { if(minVal == factors[j].first * res[factors[j].second]) factors[j].second ++; } } return res[n-1]; } };


Conjuntos de estudio relacionados

IPC Chapter 15 test (NOT ALL TRUE OR FALSE IS ON HERE)

View Set

Classical or Empirical Probability

View Set

George Washington's Presidency, 8th Grade SS

View Set

muscle structures largest to smallest

View Set

gov unit 4 reading quiz questions

View Set