Given an array flowers consists of number from 1 to N. Each number in the array represents the place where the flower will open in that day. Given an integer k, you need to output in which day there exists two flowers in the status of blooming, and also the number of flowers between them is k and these flowers are not blooming.
A position array, pos[x] = i means the flower x blooms at i day
fix left and right pointer, check if we can find an array [left, 1, 2,..., k, right] is valids
publicintkEmptySlots(int[] flowers,int k) {int len =flowers.length;int[] pos =newint[len];for(int i=0; i<len; i++){// pos[x] = i means the flower x blooms at i day pos[flowers[i]-1] = i+1; }int left =0, right = k +1;for(int i=0; Math.max(i, right) < len; i++){System.out.println(i);if(pos[left] > pos[i] || pos[right] > pos[i]){ left = i; right = left + k +1; }elseif( i == right){returnMath.max(left, right); } }return-1;}
889. Construct Binary Tree from Preorder and Postorder Traversal
Return any binary tree that matches the given preorder and postorder traversals.
Example
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
find the length of left tree and use it split the left tree and right tree
Preorder and postorder left tree length are the same, and pre[1] the head of left tree, use is to find the last position in postorder
publicTreeNodeconstructFromPrePost(int[] pre,int[] post) {// pre [1][2,4,5][3,6,7]// post [4,5,2][6,7,3][1]int len =pre.length;if(len ==0) returnnull;TreeNode node =newTreeNode(pre[0]);if(len ==1) return node;// find out the length of left treeint left_len =0;for(int i=0; i<len; i++){if(post[i] == pre[1]) left_len = i+1; }node.left=constructFromPrePost(Arrays.copyOfRange(pre,1,1+left_len),Arrays.copyOfRange(post,0, left_len));node.right=constructFromPrePost(Arrays.copyOfRange(pre,1+left_len, len),Arrays.copyOfRange(post, left_len, len-1));return node;}
280 Wiggle Sort
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
Copy the array and sort it, the number smaller than mid should put in odd slots; others should put in even slots.
publicvoidwiggleSort(int[] nums) {if (nums.length==0) return;int n =nums.length;int mid = (n+1)/2;int[] copy =Arrays.copyOf(nums, n);Arrays.sort(copy);// corner case [4,5,5,6] medium must be at head and tail// put smaller than nums[mid] elements to odd slot, start from mid-1for(int i=mid-1, j=0; i>=0; i--, j+=2) nums[j] = copy[i];// put greater than nums[mid] elements to even slot, start from n-1for(int i=n-1, j=1; i>=mid; i--, j+=2) nums[j] = copy[i];}
475 Heaters
you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.
Given an array(index start from 1), B is the step you can jump from index i. Return the path indexes starting from 1 to last index in array.
A next[] array to record the indexes
Statement: dp[i] is the min jumping cost starting from index i to end of array.
Func: dp[i] = min(A[i]+dp[i+B]) B <- 1:B
Ans: Loop the next[], if index == -1, then return empty list
publicList<Integer>cheapestJump(int[] A,int B) {int[] dp =newint[A.length];int[] next =newint[A.length-1];Arrays.fill(next,-1);for(int i=A.length-2; i>=0; i--){int cost =Integer.MAX_VALUE;for(int j=i+1; j<=i+B && j<A.length; j++){if(A[j] !=-1){if(A[i] + dp[j] < cost){ cost =A[i] + dp[j]; next[i] = j; } } } dp[i] = cost; }List<Integer> ans =newArrayList<>();int i=0;// if i is not init means it cannot proceed while(i<A.length-1&& i !=-1){System.out.println(i);ans.add(i+1); i=next[i]; }ans.add(i+1);if(i ==-1) returnnewArrayList<>();return ans;}
399. Evaluate Division
Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.
Time: O(q+ q*E), q is the number of queries, E is the connecting edges. The best case of E is 1, worst is length of equations
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
classNode{String word;int index;publicNode(String word,int index){this.word= word;this.index= index; }}publicintnumMatchingSubseq(String S,String[] words) {int count=0;Map<Character,List<Node>> map =newHashMap<>();// build the headsfor(int i=0; i<26; i++){map.put((char)('a'+ i),newArrayList<Node>()); }// initfor(String w: words){char c =w.charAt(0);map.get(c).add(newNode(w,0)); }// loop the String s// if index == word len means it got throght the whole wordfor(char c:S.toCharArray()){// list在loop過程中不能更動,不然會拋出ConcurrentModificationExceptionList<Node> list =map.get(c);map.put(c,newArrayList<>());for(Node node: list){node.index++;if(node.index==node.word.length()) count++;elsemap.get(node.word.charAt(node.index)).add(node); }list.clear(); }return count;}
835. Image Overlap
Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)
We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images.
What is the largest possible overlap?
Count the moving vector from image A to image B
Time O(n^4)
publicintlargestOverlap(int[][] A,int[][] B) {// count the moving vector from A to Bint n =A.length;int[][] vector =newint[2*n][2*n];for(int i=0; i<n; i++){for(int j=0; j<n; j++){if(A[i][j] ==1){for(int k=0; k<n; k++){for(int l=0; l<n; l++){if(B[k][l] ==1) vector[k-i+n][l-j+n]+=1; } } } } }// count the maxint max=0;for(int[] row: vector){for(int num: row){ max =Math.max(max, num); } }return max;}
328. Odd Even Linked List
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.
Return the number of the receptor that the ray meets first.
publicintmirrorReflection(int p,int q) {int m=1, n=1;while( m*p != n*q){ n++; m = n*q/p; }// if light reflection is even(n is odd), on the rhs; otherwise lhs// if box extension is even(m is odd), on 1; otherwise on 0if(m%2==0&& n%2==1) return0;if(m%2==1&& n%2==1) return1;if(m%2==1&& n%2==0) return2;return-1;}
855. Exam Room
In an exam room, there are N seats in a single row, numbered 0, 1, 2, ..., N-1.
When a student enters the room, they must sit in the seat that maximizes the distance to the closest person
Need a dynamic sorted array, use TreeSet
比較dist分三部分
array head to first seat
seat betweens
last seat to array tail
classExamRoom {TreeSet<Integer> students;int N;publicExamRoom(int N) {this.N= N; students =newTreeSet<>();; }publicintseat() {int pos =0;if(students.size() >0){// first dist is the dist from beginning to first studentint dist =students.first();Integer prev =null;for(int s: students){if(prev !=null){int tmp = (s-prev)/2;if(tmp > dist){ dist = tmp; pos = prev + tmp; } } prev = s; } // test the dist from last student to end of arrayif( (N-1) -students.last() > dist) pos = N-1; }// add pos to treeSetstudents.add(pos);return pos; }publicvoidleave(int p) {students.remove(p); }}
853. Car Fleet
N cars is array. Each car i has a constant speed speed[i] and initial position position[i]
A car can never pass another car ahead of it, if car A catch up car B, they are assumed to have the same position.
We are given a list of (axis-aligned) rectangles. Each rectangle[i] = [x1, y1, x2, y2] , where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the ith rectangle.
Find the total area covered by all rectangles in the plane. Since the answer may be too large, return it modulo 10^9 + 7.
記錄每一個rectangle 在y軸上in & out的event, 並且sort by y dimention
Use sweep line to count x distance, multiple y diff
Put 'in' event in active lit, move 'out' event
// int[0]: y1/y2, int[1]: in/out, int[2]: x1, int[3]: x2 publicintrectangleArea(int[][] rectangles) {int n =rectangles.length;List<int[]> line =newArrayList<>();for(int[] rec: rectangles){line.add(newint[]{rec[1],0, rec[0], rec[2]});line.add(newint[]{rec[3],1, rec[0], rec[2]}); }// sort by y dimentionCollections.sort(line, (a,b) -> a[0] - b[0]);int y =line.get(0)[0];long ans =0;List<int[]> intervals =newArrayList<>();for(int i=0; i<line.size(); i++){int[] cur =line.get(i);long dis =getXDistance(intervals); ans += dis*(cur[0] - y); if(cur[1] ==0){intervals.add(newint[]{cur[2], cur[3]});Collections.sort(intervals, (a,b) -> a[0] - b[0]); }else{for(int[] tmp: intervals){if(tmp[0] == cur[2] && tmp[1] == cur[3]){intervals.remove(tmp);break; } } } y = cur[0]; } ans %=1e9+7;// if(ans < 0) ans += 1e9+7;return (int)ans;}privatelonggetXDistance(List<int[]> intervals){long ans =0;int prev =-1;for(int[] cur: intervals){// prev 為上一個x2 prev =Math.max(prev, cur[0]); ans +=Math.max(cur[1]-prev,0); prev =Math.max(prev, cur[1]); }return ans;}
846. Hand of Straights
Alice has a hand of cards, given as an array of integers.
Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.
Return true if and only if she can.
Use a TreeMap to record the frequency and continuous of number
Your car starts at position 0 and speed +1 on an infinite number line. (Your car can go into negative positions.)
Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse).
When you get an instruction "A", your car does the following: position += speed, speed *= 2.
When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1. Return the shortest sequence of instructions
Recursion + memorization
DP(t): the shortest sequence to achieve target
3 condition
t is exact nA: n
t is over 2^n-1 (nA1R): n+1+helper(left)
t is reverse twice (n-1)ARmAR: (n+m+1) + helper( t - (2^(n-1)-1+2^(m)-1))
We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever.
We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
The avg of A and avg of B and C are the same.
totalSum/n = Asum/k => Asum = totalSum*k/n整除
利用combinationSum, 遞回到 k=0 && remain == 0
publicbooleansplitArraySameAverage(int[] A) {int sum=0;int n =A.length;for(int num:A) sum+=num;Arrays.sort(A);for(int i=1; i<=n/2;i++){if(sum*i%n ==0&&combinationSum(A,0, i, sum*i/n)) returntrue; }returnfalse;}privatebooleancombinationSum(int[] A,int start,int num,int remain){if(remain==0) return num ==0;if(remain<0|| num<1) returnfalse;for(int i=start; i<A.length-num+1; i++){if(combinationSum(A, i+1, num-1, remain-A[i])) returntrue; }returnfalse;}
classSolution {classUF{int[] father;publicUF(int n){ father =newint[n];for(int i=0; i<n; i++){ father[i] = i; } }publicintfind(int a){if(father[a] != a) father[a] =find(father[a]);return father[a]; }publicvoidunion(int a,int b){int f_a =find(a);int f_b =find(b); father[f_b] = f_a; } }publicint[] findRedundantDirectedConnection(int[][] edges) {int n =edges.length+1;UF uf =newUF(n);int[] candidate1 =null, candidate2 =null;for(int[] e: edges){int f_a =uf.find(e[0]), f_b =uf.find(e[1]);if(f_a != f_b){// multiple parents, means e[1] has been seen before and its parents is not itselfif(f_b != e[1]) candidate1 = e;elseuf.union(e[0], e[1]); }else{// cycle candidate2 = e; } }// if only either multiple parents or cycle happensif(candidate2 ==null) return candidate1;if(candidate1 ==null) return candidate2;// if both happen, we don't consider the 2nd multiple edge since beginning// The first edge caused multiple father must be removedfor(int[] e: edges){if(e[1] == candidate1[1]) return e; }returnnewint[2]; }}
312. Burst Balloons
Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] nums[i] nums[right] coins. Here left and right are adjacent indices of i. nums[-1] = nums[n] = 1
dp[i][j]: 第i個到第j個nums的array中, ballon burst的最大值
Trans: dp[i][j] = dp[i][k-1] + nums[i]nums[k]nums[j] + dp[k+1][j], i <= k <= j
Given the color "#ABCDEF", return a 7 character color that is most similar to #ABCDEF, and has a shorthand (that is, it can be represented as some "#XYZ")
// 要求的形式為AA, 必定為轉換後的數字為17的倍數publicStringsimilarRGB(String color) {return"#"+helper(color.substring(1,3))+helper(color.substring(3,5))+helper(color.substring(5));}privateStringhelper(String s){int num =Integer.parseInt(s,16); num = num /17+ (num %17>8?1:0);returnString.format("%02x", num *17);}