Leetcode easy
1. Two Sum
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
1st: O(n2)算法,可以用空间换时间,用hashmap存储,降到O(n)。
2nd: 细节没处理好,HashMap num.length 等。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 int [] res = new int[2]; 4 for (int i = 0; i < nums.length - 1; i++) { 5 for (int j = i + 1; j < nums.length; j++) { 6 if (nums[i] + nums[j] == target) { 7 res[0] = i; 8 res[1] = j; 9 return res; 10 } 11 } 12 } 13 return res; 14 } 15 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 Map<Integer, Integer> hash = new HashMap<Integer,Integer>(); 4 int [] res = new int[2]; 5 for (int i = 0; i < nums.length; i++) { 6 if (hash.containsKey(target - nums[i])) { 7 res[0] = hash.get(target - nums[i]); 8 res[1] = i; 9 return res; 10 } 11 hash.put(nums[i], i); 12 } 13 return res; 14 } 15 }
6. ZigZag Conversion
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string text, int nRows); convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
1 st : 索引范围没取好
按每行索引存储
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public String convert(String s, int numRows) { 3 if (s.length() < 3 || numRows == 1){ 4 return s; 5 } 6 int cycle = 2 * numRows - 2; 7 StringBuffer res = new StringBuffer(s.length()); 8 for (int i = 0; i < s.length(); i += cycle) { 9 res.append(s.charAt(i)); 10 } 11 for (int i = 1; i < numRows - 1; i++) { 12 for (int j = i; j < s.length(); j+= cycle) { 13 res.append(s.charAt(j)); 14 if (j + cycle - 2 * i < s.length()) { 15 res.append(s.charAt(j + cycle - 2 * i)); 16 } 17 } 18 } 19 for (int i = numRows - 1; i < s.length(); i += cycle) { 20 res.append(s.charAt(i)); 21 } 22 return res.toString(); 23 } 24 }
先转成char数组更快
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public String convert(String s, int numRows) { 3 if (s.length() < 3 || numRows == 1){ 4 return s; 5 } 6 char [] c = s.toCharArray(); 7 int cycle = 2 * numRows - 2; 8 StringBuffer res = new StringBuffer(s.length()); 9 for (int i = 0; i < s.length(); i += cycle) { 10 res.append(c[i]); 11 } 12 for (int i = 1; i < numRows - 1; i++) { 13 for (int j = i; j < s.length(); j+= cycle) { 14 res.append(c[j]); 15 if (j + cycle - 2 * i < s.length()) { 16 res.append(c[j + cycle - 2 * i]); 17 } 18 } 19 } 20 for (int i = numRows - 1; i < s.length(); i += cycle) { 21 res.append(c[i]); 22 } 23 return res.toString(); 24 } 25 }
或按每列存储
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public String convert(String s, int nRows) { 3 char[] c = s.toCharArray(); 4 int len = c.length; 5 StringBuffer[] sb = new StringBuffer[nRows]; 6 for (int i = 0; i < sb.length; i++){ 7 sb[i] = new StringBuffer(); 8 } 9 int i = 0; 10 while (i < len) { 11 for (int idx = 0; idx < nRows && i < len; idx++){ // vertically down 12 sb[idx].append(c[i++]); 13 } 14 for (int idx = nRows - 2; idx >= 1 && i < len; idx--){ // obliquely up 15 sb[idx].append(c[i++]); 16 } 17 } 18 for (int idx = 1; idx < sb.length; idx++) { 19 sb[0].append(sb[idx]); 20 } 21 return sb[0].toString(); 22 } 23 }
7. Reverse Integer
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321
注意溢出
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int reverse(int x) { 3 long sum = 0; 4 while(x != 0){ 5 sum = sum * 10 + x % 10; 6 x = x/10; 7 } 8 if(sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) 9 return 0; 10 return (int)sum; 11 } 12 }
或者判断乘10后,再除10是否相等。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 /** 3 * @param n the integer to be reversed 4 * @return the reversed integer 5 */ 6 public int reverseInteger(int n) { 7 int reversed_n = 0; 8 9 while (n != 0) { 10 int temp = reversed_n * 10 + n % 10; 11 n = n / 10; 12 if (temp / 10 != reversed_n) { 13 reversed_n = 0; 14 break; 15 } 16 reversed_n = temp; 17 } 18 return reversed_n; 19 } 20 }
8. String to Integer (atoi)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. spoilers alert... click to show requirements for atoi. Requirements for 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. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
注意大量的corner case, 1 str == null str.length() == 0, 溢出 空格 正负号等
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int myAtoi(String str) { 3 if (str == null || str.length() == 0) { 4 return 0; 5 } 6 long sum = 0; 7 int i = 0; 8 int positive = 1; 9 while (str.charAt(i) == ' '){ 10 i++; 11 } 12 if (str.charAt(i) == '+'){ 13 i++; 14 } else if (str.charAt(i) == '-') { 15 i++; 16 positive = -1; 17 } 18 while (i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0') { 19 sum = sum * 10 + str.charAt(i) - '0'; 20 i++; 21 if (sum > Integer.MAX_VALUE) { 22 return positive == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; 23 } 24 } 25 return positive * (int) sum; 26 } 27 }
9. Palindrome Number -- No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Determine whether an integer is a palindrome. Do this without extra space.(回文数)
注意corner case 溢出,结尾为0,其余的回文,负数等。
2nd : 判断 结尾为0。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public boolean isPalindrome(int x) { 3 if (x < 0 || ( x !=0 && x % 10 == 0)) { 4 return false; 5 } 6 int rev = 0; 7 while (rev < x) { 8 rev = rev * 10 + x % 10; 9 x = x / 10; 10 } 11 return (x == rev || x == rev / 10); 12 } 13 }
day2: 注意return判断。
13. Roman to Integer
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
按照规则,前缀的较小数减去即可。可通过map或子函数switch枚举建立映射
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int romanToInt(string s) { if (s.empty()) return 0; map<char, int> p; p['I'] = 1; p['V'] = 5; p['X'] = 10; p['L'] = 50; p['C'] = 100; p['D'] = 500; p['M'] = 1000; int len = s.size(); int ans = p[s[len-1]]; for (int i = len-2; i >= 0; i--) { if (p[s[i]] < p[s[i+1]]) { ans -= p[s[i]]; } else { ans += p[s[i]]; } } return ans; } };
14. Longest Common Prefix
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Write a function to find the longest common prefix string amongst an array of strings.
思路: 1 从头到尾一个一个字节比较。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public String longestCommonPrefix(String[] strs) { 3 if (strs.length == 0) { 4 return ""; 5 } 6 StringBuffer res = new StringBuffer(); 7 for (int i = 0; i < strs[0].length(); i++) { 8 for (int j = 1; j < strs.length; j++) { 9 if (i >= strs[j].length() || strs[j].charAt(i) != strs[0].charAt(i)) { 10 return res.toString(); 11 } 12 } 13 res.append(strs[0].charAt(i)); 14 } 15 return res.toString(); 16 } 17 }
2:前两个字符串求prefix,用此prefix与下一个str求prefix,递归。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 3 public String longestCommonPrefix(String[] strs) { 4 if (strs == null || strs.length == 0) { 5 return ""; 6 } 7 String prefix = strs[0]; 8 for(int i = 1; i < strs.length; i++) { 9 int j = 0; 10 while( j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j)) { 11 j++; 12 } 13 if( j == 0) { 14 return ""; 15 } 16 prefix = prefix.substring(0, j); 17 } 18 return prefix; 19 } 20 21 }
19. Remove Nth Node From End of List
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Try to do this in one pass.
思路: 先让一个指针先行k步即可。注意移除的是头指针这种情况。可从头指针前面加一个开始便利简化。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode removeNthFromEnd(ListNode head, int n) { 11 if (head == null) { 12 return null; 13 } 14 ListNode fast = head; 15 ListNode slow = head; 16 while (n > 0 && fast != null) { 17 fast = fast.next; 18 n--; 19 } 20 if (fast == null) { 21 return head.next; 22 } 23 while (fast.next != null) { 24 slow = slow.next; 25 fast = fast.next; 26 } 27 slow.next = slow.next.next; 28 return head; 29 } 30 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public ListNode removeNthFromEnd(ListNode head, int n) { 2 3 ListNode start = new ListNode(0); 4 ListNode slow = start, fast = start; 5 slow.next = head; 6 7 //Move fast in front so that the gap between slow and fast becomes n 8 for(int i=1; i<=n+1; i++) { 9 fast = fast.next; 10 } 11 //Move fast to the end, maintaining the gap 12 while(fast != null) { 13 slow = slow.next; 14 fast = fast.next; 15 } 16 //Skip the desired node 17 slow.next = slow.next.next; 18 return start.next; 19 }
20. Valid Parentheses -- No Bug Free
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
栈的运用。
1st: if 里判断为空 用||而非 !empty() &&
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public boolean isValid(String s) { 3 Stack<Character> stack = new Stack<>(); 4 for (int i = 0; i < s.length(); i++) { 5 char c = s.charAt(i); 6 switch (c) { 7 case ')': 8 if (stack.empty() || stack.pop() != '(') { 9 return false; 10 } 11 break; 12 case ']': 13 if (stack.empty() || stack.pop() != '[') { 14 return false; 15 } 16 break; 17 case '}': 18 if (stack.empty() || stack.pop() != '{') { 19 return false; 20 } 21 break; 22 case '{': 23 case '[': 24 case '(': 25 stack.push(c); 26 break; 27 } 28 } 29 return stack.empty(); 30 } 31 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public boolean isValid(String s) { 2 Stack<Character> stack = new Stack<Character>(); 3 for (char c : s.toCharArray()) { 4 if (c == '(') 5 stack.push(')'); 6 else if (c == '{') 7 stack.push('}'); 8 else if (c == '[') 9 stack.push(']'); 10 else if (stack.isEmpty() || stack.pop() != c) 11 return false; 12 } 13 return stack.isEmpty(); 14 }
21. Merge Two Sorted Lists
合并两个有序链表。注意考虑两个链表是否会相交
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (!l1) return l2; if(!l2) return l1; ListNode* head; if (l2->val < l1->val) { head = l2; l2 = l2->next; } else { head = l1; l1 = l1->next; } ListNode* prev = head; while (l1 && l2) { if (l1->val < l2->val) { prev->next = l1; prev = l1; l1 = l1->next; } else { prev->next = l2; prev = l2; l2 = l2->next; } } if (l1) { prev->next = l1; } else { prev -> next = l2; } return head; } };
26. Remove Duplicates from Sorted Array
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example, Given input array nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int removeDuplicates(int[] nums) { if (nums == null) { return 0; } int len = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] != nums[i - 1]) { nums[len++] = nums[i]; } } return len; } }
27. Remove Element
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. Example: Given input array nums = [3,2,2,3], val = 3 Your function should return length = 2, with the first two elements of nums being 2.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int removeElement(int[] nums, int val) { 3 int len = 0; 4 for (int num : nums) { 5 if (num != val) { 6 nums[len++] = num; 7 } 8 } 9 return len; 10 } 11 }
35. Search Insert Position
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6], 2 → 1 [1,3,5,6], 7 → 4 [1,3,5,6], 0 → 0
题意:查找有序数组中第一个不小于target的下标。。(实现lower_bound)
1:O(n)线性。。。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int searchInsert(vector<int>& nums, int target) { /*if (nums == ull) { return 0; }*/ for (int i = 0; i < nums.size(); i++) { if (nums[i] >= target) { return i; } } return nums.size(); } };
2 二分
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int searchInsert(vector<int>& nums, int target) { int left =0; int mid=0; int right = nums.size()-1; if(nums.empty()) return 0; if(target>nums[nums.size()-1]) return nums.size(); while(left<right){ mid = (left+right)/2; if(nums[mid]==target) return mid; else if(nums[mid] > target) right = mid; else left = mid + 1; } return left; } };
36. Valid Sudoku --No Bug Free
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
思路:每次外层循环同时判断一行、一列、一个九宫格。对九宫格:先找出每个格开始的位置(3 * (i/3), 3 * (i % 3))(可通过画真值表枚举)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public boolean isValidSudoku(char[][] board) { 3 for (int i = 0; i < 9; i++) { 4 HashSet<Character> row = new HashSet(); 5 HashSet<Character> col = new HashSet(); 6 HashSet<Character> cub = new HashSet(); 7 for (int j = 0; j < 9; j++) { 8 if (board[i][j] != '.' && !row.add(board[i][j])) { 9 return false; 10 } 11 if (board[j][i] != '.' && !col.add(board[j][i])) { 12 return false; 13 } 14 int rowIndex = 3 * (i / 3) + j /3; 15 int colIndex = 3 * (i % 3) + j % 3; 16 if (board[rowIndex][colIndex] != '.' && !cub.add(board[rowIndex][colIndex])) { 17 return false; 18 } 19 } 20 } 21 return true; 22 } 23 }
38. Count and Say
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represented as a string.
暴力从同开始按规律生成即可.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public String countAndSay(int n) { 3 StringBuffer res = new StringBuffer("1"); 4 for (int k = 1; k < n; k++) { 5 StringBuffer temp = new StringBuffer(); 6 for (int i = 0; i < res.length();) { 7 int j = 1; 8 while (i + j < res.length() && res.charAt(i) == res.charAt(i + j)) { 9 j++; 10 } 11 temp.append(j); 12 temp.append(res.charAt(i)); 13 i += j; 14 } 15 res = temp; 16 } 17 return res.toString(); 18 } 19 }
58. Length of Last Word
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. For example, Given s = "Hello World", return 5.
思路:注意以" "结束的字符串即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int lengthOfLastWord(String s) { if (s == null) { return 0; } int len = 0;; int i = s.length() - 1; while (i >= 0 && s.charAt(i) == ' ') { i--; } while (i >= 0 && s.charAt(i) != ' ') { len++; i--; } return len; } }
66. Plus One
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
思路:注意全是9即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 if (digits == null) { 4 return null; 5 } 6 int next = 0; 7 for (int i = digits.length - 1; i >= 0; i--) { 8 if (digits[i] < 9) { 9 digits[i] ++; 10 break; 11 } 12 next = i -1; 13 digits[i] = 0; 14 } 15 if (next != -1) { 16 return digits; 17 } 18 int[] ans = new int [digits.length + 1]; 19 ans[0] = 1; 20 for (int i = 1; i < ans.length; i++) { 21 ans[i] = digits[i - 1]; 22 } 23 return ans; 24 } 25 }
优化:不满足直接return即可,最后不用复制,因为全是0。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 int n = digits.length; 4 for(int i=n-1; i>=0; i--) { 5 if(digits[i] < 9) { 6 digits[i]++; 7 return digits; 8 } 9 digits[i] = 0; 10 } 11 int[] newNumber = new int [n+1]; 12 newNumber[0] = 1; 13 return newNumber; 14 } 15 }
67. Add Binary --No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Given two binary strings, return their sum (also a binary string). 2 3 For example, 4 a = "11" 5 b = "1" 6 Return "100".
可用 || 判断更为简洁。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public String addBinary(String a, String b) { StringBuffer ans = new StringBuffer(); int aIndex = a.length() - 1; int bIndex = b.length() - 1; int add = 0; while (aIndex >= 0 && bIndex >= 0) { int num = a.charAt(aIndex) + b.charAt(bIndex) + add - 2 * '0'; ans.append(num % 2); add = num / 2; aIndex--; bIndex--; } while (aIndex >= 0) { int num = a.charAt(aIndex) + add - '0'; ans.append(num % 2); add = num / 2; aIndex--; } while (bIndex >= 0) { int num = b.charAt(bIndex) + add - '0'; ans.append(num % 2); add = num / 2; bIndex--; } if (add == 1) { ans.append('1'); } return ans.reverse().toString(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public String addBinary(String a, String b) { 3 StringBuilder sb = new StringBuilder(); 4 int i = a.length() - 1, j = b.length() -1, carry = 0; 5 while (i >= 0 || j >= 0) { 6 int sum = carry; 7 if (j >= 0) sum += b.charAt(j--) - '0'; 8 if (i >= 0) sum += a.charAt(i--) - '0'; 9 sb.append(sum % 2); 10 carry = sum / 2; 11 } 12 if (carry != 0) sb.append(carry); 13 return sb.reverse().toString(); 14 } 15 }
69. Sqrt(x)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Implement int sqrt(int x). Compute and return the square root of x.
牛顿法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int mySqrt(int x) { long ans = x; while (ans * ans > x) { ans = (ans + x / ans) / 2; } return ans; } };
70. Climbing Stairs
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
F(n) = F(n - 1) + F(n - 2), 注意空间复杂度。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int climbStairs(int n) { if (n < 0) { return 0; } if (n < 3) { return n; } int[] dp =new int[2]; dp[0] = 1; dp[1] = 2; for (int i = 2; i < n; i++) { dp[i % 2] = dp[(i - 1) % 2] + dp[(i - 2) % 2]; } return dp[(n - 1) % 2]; } }
83. Remove Duplicates from Sorted List
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Given a sorted linked list, delete all duplicates such that each element appear only once. 2 3 For example, 4 Given 1->1->2, return 1->2. 5 Given 1->1->2->3->3, return 1->2->3
思路:比较与前一个是否相同即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode deleteDuplicates(ListNode head) { 11 if (head == null) { 12 return null; 13 } 14 ListNode cur = head.next; 15 ListNode prev = head; 16 while (cur != null) { 17 if (cur.val == prev.val) { 18 prev.next = cur.next; 19 cur = cur.next; 20 } else { 21 prev = cur; 22 cur = cur.next; 23 } 24 } 25 return head; 26 } 27 }
88. Merge Sorted Array --No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
不要从前往后,从后往前即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public void merge(int[] nums1, int m, int[] nums2, int n) { 3 int index = m - 1; 4 int index2 = n - 1; 5 int cur = m + n - 1; 6 while (index >= 0 && index2 >= 0) { 7 if (nums2[index2] >= nums1[index]) { 8 nums1[cur--] = nums2[index2--]; 9 } else { 10 nums1[cur--] = nums1[index--]; 11 } 12 } 13 while (index2 >= 0) { 14 nums1[cur--] = nums2[index2--]; 15 } 16 } 17 }
100. Same Tree
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Given two binary trees, write a function to check if they are equal or not. 2 3 Two binary trees are considered equal if they are structurally identical and the nodes have the same value
递归比较即可,可尝试用非递归。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isSameTree(TreeNode p, TreeNode q) { 12 if (p == null || q == null) { 13 return p == q; 14 } 15 return p.val == q.val && isSameTree(p.left, q.left) 16 && isSameTree(p.right, q.right); 17 } 18 }
101. Symmetric Tree
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 2 3 For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 4 5 1 6 / \ 7 2 2 8 / \ / \ 9 3 4 4 3 10 But the following [1,2,2,null,3,null,3] is not: 11 1 12 / \ 13 2 2 14 \ \ 15 3 3 16 Note: 17 Bonus points if you could solve it both recursively and iteratively.
思路:初级递归。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isSymmetric(TreeNode root) { 12 if (root == null) { 13 return true; 14 } 15 return isSymmetric(root.left, root.right); 16 } 17 private boolean isSymmetric(TreeNode node1, TreeNode node2) { 18 if (node1 == null || node2 == null) { 19 return node1 == node2; 20 } 21 return node1.val == node2.val && isSymmetric(node1.left, node2.right) 22 && isSymmetric(node1.right, node2.left); 23 } 24 }
102. Binary Tree Level Order Traversal --No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 2 3 For example: 4 Given binary tree [3,9,20,null,null,15,7], 5 3 6 / \ 7 9 20 8 / \ 9 15 7 10 return its level order traversal as: 11 [ 12 [3], 13 [9,20], 14 [15,7] 15 ]
思路:队列BFS或递归DFS
1st: 注意变量名。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList(); if (root == null) { return ans; } Queue<TreeNode> curNode = new LinkedList(); curNode.add(root); while (!curNode.isEmpty()) { List<Integer> curVal = new ArrayList(); int num = curNode.size(); for (int i = 0; i < num; i++) { TreeNode node = curNode.poll(); curVal.add(node.val); if (node.left != null) { curNode.add(node.left); } if (node.right != null) { curNode.add(node.right); } } ans.add(curVal); } return ans; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<List<Integer>>(); levelHelper(res, root, 0); return res; } public void levelHelper(List<List<Integer>> res, TreeNode root, int height) { if (root == null) return; if (height >= res.size()) { res.add(new LinkedList<Integer>()); } res.get(height).add(root.val); levelHelper(res, root.left, height+1); levelHelper(res, root.right, height+1); }
104. Maximum Depth of Binary Tree
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
DFS即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } int left = maxDepth(root.left); int right = maxDepth(root.right); if (left == 0 || right == 0) { return left + right + 1; } return Math.max(left, right) + 1; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } Queue<TreeNode> cur = new LinkedList(); cur.add(root); int depth = 0; while (! cur.isEmpty()) { depth++; int size = cur.size(); for (int i = 0; i < size; i++) { TreeNode temp = cur.poll(); if (temp.left != null) { cur.add(temp.left); } if (temp.right != null) { cur.add(temp.right); } } } return depth; } }
107. Binary Tree Level Order Traversal II
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 2 3 For example: 4 Given binary tree [3,9,20,null,null,15,7], 5 3 6 / \ 7 9 20 8 / \ 9 15 7 10 return its bottom-up level order traversal as: 11 [ 12 [15,7], 13 [9,20], 14 [3] 15 ]
BFS时每次加到前面即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<List<Integer>> levelOrderBottom(TreeNode root) { 12 LinkedList<List<Integer>> ans = new LinkedList(); 13 if (root == null) { 14 return ans; 15 } 16 Queue<TreeNode> cur = new LinkedList(); 17 cur.add(root); 18 while (!cur.isEmpty()) { 19 int num = cur.size(); 20 List<Integer> temp = new ArrayList(num); 21 for (int i = 0; i < num; i++) { 22 TreeNode node = cur.poll(); 23 temp.add(node.val); 24 if (node.left != null){ 25 cur.add(node.left); 26 } 27 if (node.right != null) { 28 cur.add(node.right); 29 } 30 } 31 ans.addFirst(temp); 32 } 33 return ans; 34 } 35 }
108. Convert Sorted Array to Binary Search Tree
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
递归处理即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { return sortedArrayToBST(nums, 0, nums.size() - 1); } TreeNode* sortedArrayToBST(vector<int>& nums, int start, int end) { if (start > end) { return nullptr; } int mid = (start + end) / 2; TreeNode* ret = new TreeNode(nums[mid]); ret->left = sortedArrayToBST(nums, start, mid - 1); ret->right = sortedArrayToBST(nums, mid + 1, end); return ret; } };
110. Balanced Binary Tree --No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
思路:递归判断,可在返回子树深度时同时判断是否平衡(返回-1则不平衡)。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Not BEST ANS * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { if (root == null) { return true; } int depth = depth(root.left, 0) - depth(root.right, 0); if (depth < -1 || depth > 1) { return false; } return isBalanced(root.left) && isBalanced(root.right); } private int depth(TreeNode node, int level) { if (node == null) { return level; } else { return Math.max(depth(node.left, level + 1), depth(node.right, level + 1)); } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Not BEST ANS * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { return depth(root) != -1; } private int depth(TreeNode node) { if (node == null) { return 0; } int lDepth = depth(node.left); if (lDepth == -1){ return -1; } int rDepth = depth(node.right); if (rDepth == -1) { return -1; } if (lDepth - rDepth < -1 || lDepth - rDepth > 1) { return -1; } return Math.max(lDepth, rDepth) + 1; } }
111. Minimum Depth of Binary Tree -- No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
思路:到叶子节点的最短路径。
1:DFS, 1st:注意把每层的节点poll完。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int minDepth(TreeNode root) { if (root == null) { return 0; } Queue<TreeNode> cur = new LinkedList<TreeNode>(); cur.add(root); int depth = 0; while (true) { depth++; int size = cur.size(); for (int i = 0; i < size; i++) { TreeNode node = cur.poll(); if (node.left == null && node.right == null) { return depth; } if (node.left != null) { cur.add(node.left); } if (node.right != null) { cur.add(node.right); } } } } }
2:递归。 1st:注意有一边为空时 返回另一边深度+1。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int minDepth(TreeNode root) { if (root == null) { return 0; } int left = minDepth(root.left); int right = minDepth(root.right); if (left == 0 || right == 0) { return left + right + 1; } return Math.min(left, right) + 1; } }
112. Path Sum --No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
注意到叶子节点才能判断是否符合(中间小于0了后面还能补回来,不能提前结束)。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } int remain = sum - root.val; if (root.left == null && root.right == null) { return remain == 0; } return hasPathSum(root.left, remain) || hasPathSum(root.right, remain); } }
119. Pascal's Triangle II -- No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space?
递推即可,第n层:a[n][i] = a[n - 1][i] + a[n - 1][i - 1],所有层可共用一个数组。
1st:注意ArrayList的add和set的不同。修改应用set,可从第一层迭代。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public List<Integer> getRow(int rowIndex) { ArrayList<Integer> ans = new ArrayList<Integer>(rowIndex + 1); ans.add(1); if (rowIndex < 1) { return ans; } ans.add(1); for (int i = 2; i <= rowIndex; i++) { ans.add(i, 1); for (int j = i - 1; j > 0; j--) { ans.set(j, ans.get(j) + ans.get(j - 1)); } } return ans; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static List<Integer> getRow2(int rowIndex) { List<Integer> ret = new ArrayList<Integer>(); ret.add(1); for (int i = 1; i <= rowIndex; i++) { for (int j = i - 1; j >= 1; j--) { int tmp = ret.get(j - 1) + ret.get(j); ret.set(j, tmp); } ret.add(1); } return ret; }
121. Best Time to Buy and Sell Stock --No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
思路:遍历找最小以及最大差即可。
1st:数组异常判断必须同时判断 == null && length == 0.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) { return 0; } int min = prices[0]; int profit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] < min) { min = prices[i]; } else if (prices[i] - min > profit) { profit = prices[i] - min; } } return profit; } }
122. Best Time to Buy and Sell Stock II
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
看了半天没看懂题意。。。。。看完才发现意思是手上最多一支股。比如[4,3,5,6]: 5-3+6-5=3 而不是6×3-3-4-5=6.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int maxProfit(int[] prices) { int total = 0; for (int i=0; i< prices.length-1; i++) { if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i]; } return total; }
若是第二种,可用优先级队列(盈利就卖同时假设买入即可)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<bits/stdc++.h> 2 using namespace std; 3 int main() { 4 int n; 5 cin >> n; 6 vector<int> prices(n); 7 for (int i = 0; i < n; i++) { 8 cin >> prices[i]; 9 } 10 priority_queue<int, vector<int>, greater<int> > q; 11 int ans = 0; 12 for (int price : prices) { 13 while (!q.empty() && price > q.top()) { 14 ans += price - q.top(); 15 q.pop(); 16 q.push(price); 17 } 18 q.push(price); 19 } 20 cout << ans << "\n"; 21 }
更简单的办法:从后往前扫,记录当前时刻股票能卖的最高价即可。 sell[n-1] = max(sell[n], a[n])
125. Valid Palindrome
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome.
思路:双指针判断头和尾是否相等即可,注意不区分大小写和无视非数字字母。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public boolean isPalindrome(String s) { if (s == null || s.length() == 0) { return true; } int i = 0; int j = s.length() - 1; while (i < j) { while (!isalph(i, s)) { i++; } while (!isalph(j, s)) { j--; } if( i >= j) { return true; } if (!equals(i, j, s)) { return false; } i++; j--; } return true; } private boolean equals(int i, int j, String s) { char a = s.charAt(i); char b = s.charAt(j); if (a >= 'a' && a <= 'z') { return a == b || a - 'a' == b - 'A'; } else if (a >= 'A' && a <= 'Z') { return a == b || a - 'A' == b - 'a'; } else if (a >= '0' && a <= '9') { return a == b; } return false; } private boolean isalph(int i, String s) { if(i >= s.length() || i < 0){ return true; // true not false !! } //System.out.println(i); char a = s.charAt(i); return (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z') || (a >= '0' && a <= '9'); } }
136. Single Number
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
异或即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int singleNumber(int[] nums) { int ans = nums[0]; for (int i = 1; i < nums.length; i++) { ans ^= nums[i]; } return ans; } }
141. Linked List Cycle --NO
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space?
快慢指针。
1st:注意条件判断。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) { return true; } } return false; } }
155. Min Stack --No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.
思路: 1:双栈,第一个正常push,pop,第二个存最小,当第一个pop的值等于第二个的peek时,第二个也pop(更新最小值)。
1st:两个都是Integer时用equals。(-127 - 128).
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class MinStack { /** initialize your data structure here. */ private Stack<Integer> normal = new Stack(); private Stack<Integer> min = new Stack(); public MinStack() { } public void push(int x) { normal.push(x); if (min.isEmpty() || x <= min.peek()) { min.push(x); } } public void pop() { if (min.peek().equals(normal.pop())) { // can't == min.pop(); } //normal.pop(); } public int top() { return normal.peek(); } public int getMin() { return min.peek(); } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
2:两个栈合并成一个栈,当最小值改变时将原来的最小值存进栈里,用另一个变量存现在的min。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class MinStack { /** initialize your data structure here. */ private int min = Integer.MAX_VALUE; private Stack<Integer> stack; public MinStack() { stack = new Stack(); } public void push(int x) { if (x <= min) { stack.push(min); min = x; } stack.push(x); } public void pop() { if (stack.pop() == min) { min = stack.pop(); } } public int top() { return stack.peek(); } public int getMin() { return min; } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
3 一个栈,存最小值与入栈值的差值,小于零是更新最小值。
165. Compare Version Numbers -- No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Compare two version numbers version1 and version2. If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate number sequences. For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. Here is an example of version numbers ordering: 0.1 < 1.1 < 1.2 < 13.37
版本号比较。
1:分别求小数点前后的数,然后比较。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int compareVersion(String version1, String version2) { int i = 0; int j = 0; int num1 = 0; int num2 = 0; while (i < version1.length() || j < version2.length()) { while (i < version1.length() && version1.charAt(i) != '.') { num1 = num1 * 10 + version1.charAt(i) - '0'; i++; } while (j < version2.length() && version2.charAt(j) != '.') { num2 = num2 * 10 + version2.charAt(j) - '0'; j++; } if (num1 != num2) { return num1 > num2 ? 1 : -1; } num1 = 0; num2 = 0; i++; j++; } return 0; } }
2: 逐个比较,可避免一个数字很长,一个数字很短。(较多corner case, not solved)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int compareVersion(String version1, String version2) { int i = 0; int j = 0; int num1 = 0; int num2 = 0; while (i < version1.length() && j < version2.length()) { char a = version1.charAt(i); char b = version2.charAt(j); if (a == '.') { if (b == '.') { break; } return -1; } else if (b == '.') { return 1; } num1 = num1 * 10 + a - '0'; num2 = num2 * 10 + b - '0'; i++; j++; } if (num1 != num2) { return num1 > num2 ? 1 : -1; } while (i < version1.length() && j < version2.length()) { if (version1.charAt(i) != version2.charAt(j)) { return version1.charAt(i) > version2.charAt(j) ? 1 : -1; } i++; j++; } if (j < version2.length()){ return 1; } else if (i < version1.length()){ return -1; } return 0; } }
167. Two Sum II - Input array is sorted
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2
双指针分别从0, n-1往中间夹逼即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int lo = 0, hi = numbers.size()-1; while (lo < hi) { int sub = target - numbers[lo]-numbers[hi]; if (sub==0) { break; } else if (sub < 0) { hi--; } else { lo++; } } return vector<int>{lo+1, hi+1}; } };
168. Excel Sheet Column Title -- No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
思路:26进制,注意从一开始,所以每次计算减一。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public String convertToTitle(int n) { StringBuffer ans = new StringBuffer(); while (n > 0) { int div = (n - 1) % 26; n = (n - 1) / 26; ans.append((char)(div + 'A')); } return ans.reverse().toString(); } }
169. Majority Element
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
思路:兑子法。将超过 n / 2的与其他的一一换掉,剩下的仍为 n / 2。(若不一定存在,则需在遍历一遍计算出现次数)。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int majorityElement(int[] nums) { int maj = 0; int count = 0; for (int num : nums) { if (count == 0) { maj = num; count++; } else if (maj == num) { count++; } else { count--; } } return maj; } }
171. Excel Sheet Column Number
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Related to question Excel Sheet Column Title 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
思路:与168类似即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int titleToNumber(String s) { int num = 0; char [] cs = s.toCharArray(); for (char c : cs) { num = num * 26 + c - 'A' + 1; } return num; } }
172. Factorial Trailing Zeroes -- No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity.
思路: 有多少个5,后面就有多少个0。(注意25有两个5)
1 :迭代5的倍数分别求有多少个,然后累加。(O(n)) -- TLE
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int trailingZeroes(int n) { int count = 0; for (int i = 5; i <= n; i += 5) { int num = i; while (num % 5 == 0) { num = num / 5; count++; } } return count; } }
2 : ans = n / 5 + n / 25 + n / 125 + n / 625..... (for循环注意溢出)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int trailingZeroes(int n) { int count = 0; for (long i = 5; i <= n; i *= 5) { count += n / i; } return count; } }
或者 n 累除 5。无溢出。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int trailingZeroes(int n) { int count = 0; while (n > 0) { n = n / 5; count += n; } return count; } }
或者 递归。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int trailingZeroes(int n) { if ( n == 0) { return 0; } return n / 5 + trailingZeroes( n / 5); } }
189. Rotate Array --No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. [show hint] Hint: Could you do it in-place with O(1) extra space? Related problem: Reverse Words in a String II
1: 循环移位,注意可能刚好成多个圈(如 n = 6, k =2),终止条件:计算更新次数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public void rotate(int[] nums, int k) { if (nums == null) { return; } int n = nums.length; int cnt = 0; int start = 0; while (cnt < n) { int index = start; int cache = nums[index]; do { index = (index + k) % n; int temp = cache; //swap next_index and cache cache = nums[index]; nums[index] = temp; cnt++; } while (index != start); start++; } } }
2: 多次reverse。注意先对K取余。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public void rotate(int[] nums, int k) { if (nums == null) { return; } k = k % nums.length; reverse(nums, 0, nums.length - 1); reverse(nums, 0, k - 1); reverse(nums, k, nums.length - 1); } private void reverse(int[] nums, int start, int end) { while (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } }
190. Reverse Bits --No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). Follow up: If this function is called many times, how would you optimize it? Related problem: Reverse Integer
思路:一直移位求最后一位然后累积即可,注意为unsigned,要用位操作,不能够*。
1st: 循环够32次, << & 优先级比 + 低。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int ans = 0; for (int i = 0; i < 32;i ++) { ans = (ans << 1) + (n & 1); n = n >> 1; } return ans; } }
202 Happy Number --No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example: 19 is a happy number 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
思路1: hashtable存求和值,直至某数出现两次或出现1.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public boolean isHappy(int n) { Set<Integer> set = new HashSet(); int sum = n; while (true) { sum = getSqureSum(sum); if (sum == 1) { return true; } if (set.contains(sum)) { return false; } set.add(sum); } } private int getSqureSum(int n) { int sum = 0; while (n > 0) { sum += (n % 10) * (n % 10); n /= 10; } return sum; } }
2 归为判断是否有环,快慢指针,出现1或重合停止.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public boolean isHappy(int n) { int fast = n; int slow = n; while (true) { slow = getSqureSum(slow); fast = getSqureSum(fast); fast = getSqureSum(fast); if (slow == 1 || fast == 1) { return true; } if (slow == fast) { return false; } } } private int getSqureSum(int n) { int sum = 0; while (n > 0) { int temp = n % 10; sum += temp * temp; n /= 10; } return sum; } }
204. Count Primes
筛法求素数即可。
1 一般筛O(n*(lglgn))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int countPrimes(int n) { vector<bool> prime(n, true); int cnt = 0; for (int i = 2; i < n; i++) { if (prime[i]) { cnt++; for (int j = 2; j*i < n; j++) { prime[j*i] = false; } } } return cnt; } };
2 线性欧拉筛O(n)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
int findPrime1(int n) { vector<bool> prime(n + 1, true); vector<int> primeList(n+1); int primeCount = 0; for (int i = 2; i <= n; i++) { if (prime[i]) { primeCount++; primeList[primeCount] = i; } for (int j = 1; j <= primeCount; j++) { if (i*primeList[j] > n) break; prime[i*primeList[j]] = false; if (i%primeList[j] == 0) break; } } return primeCount; }
278. First Bad Version
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
二分即可, 注意mid =(hi+lo) / 2会溢出, mid = lo + (hi-lo) / 2 即可。 不能mid = lo /2 + hi / 2
二分时注意移动
1 lo < hi hi = mid or li = mid+1 (cppreference upper_bound) ,最后 hi = lo
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int lo = 1, hi = n; while (lo < hi) { int mid = lo + (hi-lo)/2; if (isBadVersion(mid)) { hi = mid; } else { lo = mid + 1; } } return lo; } };
2 lo <= hi hi = mid-1 or li = mid+1 , 最后 hi = lo -1
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int lo = 1, hi = n; while (lo <= hi) { int mid = lo + (hi-lo)/2; if (isBadVersion(mid)) { hi = mid-1; } else { lo = mid + 1; } } return lo; } };
283. Move Zeroes
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: You must do this in-place without making a copy of the array. Minimize the total number of operations.
利用指针,非0元素填充,之后的全为0即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: void moveZeroes(vector<int>& nums) { int index = 0; int n = nums.size(); for (int i = 0; i < n; i++) { if (nums[i] != 0) { nums[index++] = nums[i]; } } for (; index < n; index++) { nums[index] = 0; } } };
461. Hamming Distance
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int hammingDistance(int x, int y) { int ans = 0; while (x || y) { ans += (x&1) ^ (y&1); x >>=1; y >>= 1; } return ans; } };
按位比较即可,或者先异或。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int hammingDistance(int x, int y) { int ans = 0; while (x || y) { ans += (x&1) ^ (y&1); x >>=1; y >>= 1; } return ans; } };
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int hammingDistance(int x, int y) { int ans = 0; int xy = x ^ y; while (xy) { ans += xy&1; xy >>=1; } return ans; } };
476. Number Complement --No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Note: The given integer is guaranteed to fit within the range of a 32-bit signed integer. You could assume no leading zero bit in the integer’s binary representation. Example 1: Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. Example 2: Input: 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0
按位操作即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int findComplement(int num) { int ans = 0; int i = 0; while (num) { //ans += (!(num&1)) << i; !!!! if ((num&1) == 0) { ans += 1 << i; } i++; num >>= 1; } return ans; } };
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int findComplement(int num) { unsigned mask = ~0; while (num&mask) { mask <<=1; } return ~mask & ~num; // ~(mask|| num) !!!! } };
561. Array Partition I --2 No
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Example 1: Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). Note: n is a positive integer, which is in the range of [1, 10000]. All the integers in the array will be in the range of [-10000, 10000].
1 排序取偶数位 O(nlgn)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int arrayPairSum(vector<int>& nums) { int res = 0; sort(nums.begin(),nums.end()); for(int i =0; i<nums.size(); i+=2){ res += nums[i]; } return res; } };
2 空间换时间 vector统计出现次数。 注意
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int arrayPairSum(vector<int>& nums) { vector<int> hash(20001); for (int num : nums) { hash[num+10000]++; } bool even = true; int ans = 0; for (int i = 0; i < 20001; i++) { if (hash[i]) { ans += (i - 10000) * (hash[i] / 2); if (hash[i] % 2) { ans += even ? (i - 10000) : 0; even = !even; } } } return ans; } };
575. Distribute Candies
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain. Example 1: Input: candies = [1,1,2,2,3,3] Output: 3 Explanation: There are three different kinds of candies (1, 2 and 3), and two candies for each kind. Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. The sister has three different kinds of candies. Example 2: Input: candies = [1,1,2,3] Output: 2 Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The sister has two different kinds of candies, the brother has only one kind of candies. Note: The length of the given array is in range [2, 10,000], and will be even. The number in given array is in range [-100,000, 100,000].
用set或bitset数组统计出现种类数即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int distributeCandies(vector<int>& candies) { vector<bool> hash(200001, false); int cnt = 0; for (int candy : candies) { if (!hash[candy+100000]) { cnt++; hash[candy+100000] = true; if (cnt == candies.size()/2) { return cnt; } } } return cnt; } };
617. Merge Two Binary Trees
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Example 1: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7 Note: The merging process must start from the root nodes of both trees.
递归即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { if (!t2) return t1; if (!t1) return t2; TreeNode* root = new TreeNode(t1->val + t2->val); root->left = mergeTrees(t1->left, t2->left); root->right = mergeTrees(t1->right, t2->right); return root; } };
665. Non-decreasing Array
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n). Example 1: Input: [4,2,3] Output: True Explanation: You could modify the first 4 to 1 to get a non-decreasing array. Example 2: Input: [4,2,1] Output: False Explanation: You can't get a non-decreasing array by modify at most one element. Note: The n belongs to [1, 10,000].
遍历即可,找到第一个下降点nums[i] < nums[i-1], 此时有两种选择:升高nums[i] 或降低nums[i-1], 由于应让nums[i]尽可能小, 所以优先降低nums[i-1]。(由于最多降到nums[i-2],所以nums[i-2]应<=nums[i])。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: bool checkPossibility(vector<int>& nums) { int n = nums.size(); bool modify = false; for (int i = 1; i < n; i++) { if (nums[i] < nums[i-1]) { if (modify) return false; if (i != 1 && nums[i-2] > nums[i]) { nums[i] = nums[i-1]; } else { nums[i-1] = nums[i]; } modify = true; } } return true; } };
657. Judge Route Circle
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: bool judgeCircle(string moves) { int u = 0, r = 0; for (char c : moves) { if (c == 'U') { u++; } else if (c == 'D') { u--; } else if (c == 'R') { r++; } else { r--; } } return u==0 && r==0; } };