Leetcode-W1,2
week 1
双指针(题号:167):https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int left=0; int right=numbers.size() - 1; while(right > left){ if(numbers[left] + numbers[right] == target) return {left+1,right+1}; else if(numbers[left] + numbers[right] > target) right--; else left++; } return {}; } };
排序:
快速选择、堆排序(题号:215):https://leetcode.com/problems/kth-largest-element-in-an-array/description/
Input: [3,2,3,1,2,4,5,5,6]
and k = 4
Output: 4
1.quickSelect:
class Solution { public void Sort(int[] t, int left,int right) { if(left>right) return ; int i = left; int j = right; int temp = t[left]; while(i<j) { while(t[j]>=temp && i<j) j--; while(t[i]<=temp && i<j) i++; if(i<j) swap(t,i,j); } t[left] = t[i]; t[i] = temp; Sort(t,left,i-1); Sort(t,i+1,right); } public void swap(int[] t, int a, int b){ int temp = t[a]; t[a] = t[b]; t[b] = temp; } public int findKthLargest(int[] nums, int k) { if(nums==null || nums.length<k) return -1; int n = nums.length; Sort(nums,0,n-1); return nums[n-k]; } }
class Solution { public int findKthLargest(int[] nums, int k) { int i = 0; int j = nums.length - 1; int partitionIdx; while(i <= j){ partitionIdx = partition(nums, i, j); if((k - 1) == partitionIdx){ return nums[partitionIdx]; } else if((k -1) < partitionIdx){ j = partitionIdx - 1; } else{ i = partitionIdx + 1; } } return 0; } public int partition(int[] nums, int start, int end){ if(start == end){ return start; } int pivot = nums[start]; while(start < end){ while(start < end && nums[end] <= pivot){ end--; } nums[start] = nums[end]; while(start < end && nums[start] >= pivot){ start++; } nums[end] = nums[start]; } nums[start] = pivot; return start; } }
2.Heap(priorityQueue)
class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>(); for(int val : nums) { pq.offer(val); if(pq.size() > k) { pq.poll(); } } return pq.peek(); } }
class Solution { public: int findKthLargest(vector<int>& nums, int k) { // min heap priority_queue< int, vector<int>, greater<int> > pq; // add first k elements to heap, since min heap, min element will be at top for (int i=0; i<k; ++i) { pq.push(nums[i]); } // for rest of elements... // ... if it is greater than heap's top... // ... pop from heap and push num to heap // thereby maintaining heap size to be (k) // one by one, all numbers in heap become the (k) largest numbers in array for (int i=k; i<nums.size(); ++i) { if (nums[i] > pq.top()) { pq.pop(); pq.push(nums[i]); } } // at the end, the number at top will be less than all numbers in heap // that is, it will be kth largest return pq.top(); } };
桶排序(题号:347):https://leetcode.com/problems/top-k-frequent-elements/description/
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int,int> um; // map number frequency for (int c: nums) um[c]++; priority_queue< pair<int,int> > pq; // max heap by frequency,默认大顶堆 for (auto i: um) pq.push(make_pair(i.second,i.first)); vector<int> ans; // for each element of heap, // add that num to answer while (k--) { auto x = pq.top(); pq.pop(); ans.push_back(x.second); } return ans; }
荷兰国旗问题(题号:75):https://leetcode.com/problems/sort-colors/description/
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
void sortColors(vector<int>& nums) { int end_zero=0; int end_one=0; int end_two=0; int n=nums.size(); for(int i=0;i<n;i++){ switch(nums[i]){ case 0: swap(nums[i],nums[end_zero]); end_zero++; if(nums[i]!=1){ end_one++; end_two++; break; } case 1: swap(nums[i],nums[end_one]); end_one++; end_two++; break; case 2: swap(nums[i],nums[end_two]); end_two++; break; i++; } }
贪心(题号:455):https://leetcode.com/problems/assign-cookies/description/
Input: [1,2], [1,2,3]
Output: 2
int findContentChildren(vector<int>& g, vector<int>& s) { int contentLevel = 0; sort(g.begin(), g.end(), greater<int>()); //sort in reverse for easier popping sort(s.begin(), s.end(), greater<int>()); while(g.size() > 0 && s.size() > 0){//just a greedy algorithm where both are consumed if(g[g.size()-1] > s[s.size()-1])//when satisfaction is greater than greed s.pop_back(); else{ s.pop_back(); g.pop_back(); contentLevel++; } } return contentLevel; }
二分(题号:69):https://leetcode.com/problems/sqrtx/description/
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842...
public int mySqrt(int x) { if (x <= 0) return 0; long res = x; while (res * res > x) res = (res + x/res) / 2; return (int)res; }
分治(题号:241):https://leetcode.com/problems/different-ways-to-add-parentheses/description/
Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation:
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
class Solution { private Map<String, List<Integer>> resultMap = new HashMap<>(); public List<Integer> diffWaysToCompute(String input) { if (resultMap.containsKey(input)) return resultMap.get(input); List<Integer> ans = new ArrayList<>(); for (int i = 0; i < input.length(); i ++) { char op = input.charAt(i); if (op == '+' || op == '-' || op == '*') { String left = input.substring(0, i); String right = input.substring(i + 1); List<Integer> l = diffWaysToCompute(left); List<Integer> r = diffWaysToCompute(right); switch (op) { case '+': { for (int a : l) for (int b : r) ans.add(a + b); break; } case '-': { for (int a : l) for (int b : r) ans.add(a - b); break; } case '*': { for (int a : l) for (int b : r) ans.add(a * b); break; } } } } if (ans.size() == 0) ans.add(Integer.valueOf(input)); resultMap.put(input, ans); return ans; } }
链表(题号:160):https://leetcode.com/problems/intersection-of-two-linked-lists/description/
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA==null || headB==null){return null;} Set set=new HashSet(); while(headA!=null){ set.add(headA); headA=headA.next; } while(headB!=null){ if(set.contains(headB)){return headB;} headB=headB.next; } return null; }
哈希表(题号:1):https://leetcode.com/problems/two-sum/description/
Given nums = [2, 7, 11, 15], target = 9
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]
public int[] twoSum(int[] nums, int target) { Map<Integer,Integer> index = new HashMap<>(); int len = nums.length; int pair[] = new int[2]; for(int i = 0 ; i < len ; i++){ if(null != index.get((target-nums[i]))){ pair[1] = i; pair[0] = index.get((target-nums[i])); return pair; } else{ index.put(nums[i],i); } } return pair; }
字符串(题号:242):https://leetcode.com/problems/valid-anagram/description/
Input: s = "anagram", t = "nagaram"
Output: true
public boolean isAnagram(String s, String t) { int[] cntS = new int[256]; int[] cntT = new int[256]; for (char c : s.toCharArray()) { cntS[c]++; } for (char c : t.toCharArray()) { cntT[c]++; } for (int i = 0; i < 256; i++) { if (cntS[i] != cntT[i]) { return false; } } return true; }
栈和队列(题号:232):https://leetcode.com/problems/implement-queue-using-stacks/description/
public class MyQueue { Stack<Integer> stack; /** * Initialize your data structure here. */ public MyQueue() { stack = new Stack<>(); } /** * Push element x to the back of queue. */ public void push(int x) { stack.add(x); } /** * Removes the element from in front of queue and returns that element. */ public int pop() { if (!empty()) { Iterator<Integer> it = stack.iterator(); while (it.hasNext()) { Integer value = it.next(); if (!it.hasNext()) ; it.remove(); return value; } } return Integer.parseInt(null); } /** * Get the front element. */ public int peek() { if (!empty()) { Iterator<Integer> it = stack.iterator(); while (it.hasNext()) { Integer value = it.next(); if (!it.hasNext()) ; return value; } } return Integer.parseInt(null); } /** * Returns whether the queue is empty. */ public boolean empty() { return stack.empty(); } }
week 2
字符串:409. Longest Palindrome(回文) https://leetcode.com/problems/longest-palindrome/description/
Input: "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7
public int longestPalindrome(String s) { if(s.length()==0) return 0; int[] chars=new int[128]; for(char c:s.toCharArray()) chars[c]++; int cnt=0; for(int i=0;i<128;i++) cnt+=chars[i]/2; cnt=cnt*2; return cnt==s.length()?cnt:cnt+1;//如果不是全部用光偶数个,那一定有一个可以放中间 }
数组和矩阵:378. Kth Smallest Element in a Sorted Matrix https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/
public int kthSmallest(int[][] matrix, int k) { if(matrix.length * matrix[0].length < k) return -1; PriorityQueue<Integer> q=new PriorityQueue<Integer>(k,Comparator.reverseOrder()); int len=0; for(int i=0;i<matrix.length;i++){ for(int j=0;j<matrix[0].length;j++){ if(len<k){ q.offer(matrix[i][j]); len++; }else if (q.peek() > matrix[i][j]) { q.poll(); q.offer(matrix[i][j]); } } } return q.peek(); }
位运算:260. Single Number III https://leetcode.com/problems/single-number-iii/description/
Input: [1,2,1,3,2,5]
Output: [3,5]
public int[] singleNumber(int[] items) { int[] result = new int[2]; int xor = 0; for(int i : items){ xor ^= i; } xor &= ~(xor - 1); for(int i : items){ if((i&xor) != 0){ result[0] ^= i; } else{ result[1] ^= i; } } return result; }
数学
进制转换:转化为7进制 https://leetcode.com/problems/base-7/description/
public String convertToBase7(int num) { String result = ""; int q = num; int r; boolean isNeg = false; if(q < 0) { q = Math.abs(q); isNeg = true; } do { r = q % 7; q /= 7; result += r; } while (q != 0); if (isNeg) return "-" + reverse(result); else return reverse(result); } public String reverse(String input){ byte [] bytes = input.getBytes(); byte [] result = new byte [bytes.length]; for (int i = 0; i < bytes.length; i++) result[i] = bytes[bytes.length-i-1]; return new String(result); }
相遇问题:462. Minimum Moves to Equal Array Elements II https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/
Input:[1,2,3]
Output:2
Explanation:Only two moves are needed (remember each move increments or decrements one element):[1,2,3] => [2,2,3] => [2,2,2]
public int minMoves2(int[] A) { int sum = 0, median = quickselect(A, A.length/2+1, 0, A.length-1); for (int i=0;i<A.length;i++) sum += Math.abs(A[i] - median); return sum; } public int quickselect(int[] A, int k, int start, int end) { int l = start, r = end, pivot = A[(l+r)/2]; while (l<=r) { while (A[l] < pivot) l++; while (A[r] > pivot) r--; if (l>=r) break; swap(A, l++, r--); } if (l-start+1 > k) return quickselect(A, k, start, l-1); if (l-start+1 == k && l==r) return A[l]; return quickselect(A, k-r+start-1, r+1, end); } public void swap(int[] A, int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; }
多数投票问题:169. Majority Element https://leetcode.com/problems/majority-element/description/
public int majorityElement(int[] num) { // O(n) time O(1) space int major=num[0], count = 1; for(int i=1; i<num.length;i++){ if(count==0){ count++; major=num[i]; }else if(major==num[i]){ count++; }else count--; } return major; }