Follow up: What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
Constraints:
The number of elements of the BST is between 1 to 10^4.
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ //找左边最大路径或者右边最大路径和拐点(根节点)的值 classSolution{ int res;//全局变量有值传递和引用传递的区别 publicintmaxPathSum(TreeNode root){ if (root == null) return0; res = Integer.MIN_VALUE;//求最大值就是 和最小值进行比较 helper(root); return res; } publicinthelper(TreeNode root){ if (root == null) return0; int left = Math.max(0, helper(root.left));//在这里只取正数 int right = Math.max(0, helper(root.right)); res = Math.max(res, left + right + root.val); return Math.max(left ,right) + root.val; } }
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
Example 1:
1 2 3
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6.
Example 2:
1 2 3
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
Note:
All of the nodes’ values will be unique.
p and q are different and both values will exist in the BST.
publicBSTIterator(TreeNode root){ cur = root; stack = new Stack<>(); } /** @return whether we have a next smallest number */ publicbooleanhasNext(){ if (!stack.isEmpty() || cur != null) { returntrue; } returnfalse; }
/** @return the next smallest number */ publicintnext(){ while (cur != null) { stack.push(cur); cur = cur.left; } cur = stack.pop(); int val = cur.val; cur = cur.right; return val; } }
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
1 2 3 4 5 6 7
Input: [1,2,3]
1 / \ 2 3
Output: 6
Example 2:
1 2 3 4 5 6 7 8 9
Input: [-10,9,20,null,null,15,7]
-10 / \ 9 20 / \ 15 7
Output: 42
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//找左边最大路径或者右边最大路径和拐点(根节点)的值 classSolution{ int res;//全局变量有值传递和引用传递的区别 publicintmaxPathSum(TreeNode root){ if (root == null) return0; res = Integer.MIN_VALUE;//求最大值就是 和最小值进行比较 helper(root); return res; } publicinthelper(TreeNode root){ if (root == null) return0; int left = Math.max(0, helper(root.left));//在这里只取正数 int right = Math.max(0, helper(root.right)); res = Math.max(res, left + right + root.val); return Math.max(left ,right) + root.val; } }
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
Example 1:
1 2 3
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:
1 2 3
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Note:
All of the nodes’ values will be unique.
p and q are different and both values will exist in the binary tree.
1 2 3 4 5 6 7 8 9 10 11 12 13
//Preorder是从上到下,Postorder是从下到上 //typical, needs to be memorized classSolution{ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){ if (root == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) { return root; } return left == null ? right : left;//叶子节点,或者单子树节点 } }
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
1 2 3 4 5 6 7 8 9
Input: [1,2,3] 1 / \ 2 3 Output: 25 Explanation: The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Therefore, sum = 12 + 13 = 25.
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12
Input: [4,9,0,5,1] 4 / \ 9 0 / \ 5 1 Output: 1026 Explanation: The root-to-leaf path 4->9->5 represents the number 495. The root-to-leaf path 4->9->1 represents the number 491. The root-to-leaf path 4->0 represents the number 40. Therefore, sum = 495 + 491 + 40 = 1026.
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example: Given binary tree [3,9,20,null,null,15,7],
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)
1 2 3
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:
1
string convert(string s, int numRows);
Example 1:
1 2
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:
1 2 3 4 5 6 7 8
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation:
P I N A L S I G Y A H R P I
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution{ public String convert(String s, int numRows){ if (numRows <= 1) return s; StringBuilder[] sb = new StringBuilder[numRows]; for(int i = 0; i < sb.length; i++) { sb[i] = new StringBuilder(""); } for (int i = 0; i < s.length(); i++) { int index = i % (2 * numRows - 2); index = index < numRows ? index : 2 * numRows - 2 - index; sb[index].append(s.charAt(i)); } for (int i = 1; i < sb.length; i++) { sb[0].append(sb[i]); } return sb[0].toString(); } }
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
classSolution{ publicbooleanisPalindrome(String s){ if (s == null || s.length() == 0) returntrue; int left = 0; int right = s.length() - 1; //判断里面是否为数字或者字母 while (left < right) { while (left < right && !Character.isLetterOrDigit(s.charAt(left))) { left++; } while (left < right && !Character.isLetterOrDigit(s.charAt(right))) { right--; } if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { returnfalse; } left++; right--; } returntrue; } }
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
Example:
1 2
Input: [1,2,1,3,2,5] Output: [3,5]
Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
1 2 3
Input: nums = [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
1 2 3
Input: nums = [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
Constraints:
1 <= nums.length <= 3 * 10^4
0 <= nums[i][j] <= 10^5
1 2 3 4 5 6 7 8 9 10 11 12 13
//greedy 贪心思想 //max代表当前能跳的最大步数 classSolution{ publicbooleancanJump(int[] nums){ int max = 0;//max代表当前能跳的最大步数
for (int i = 0; i < nums.length; i++) { if (i > max) returnfalse; max = Math.max(nums[i] + i, max); } returntrue; } }
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Example 1:
1 2 3
Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
1 2 3 4
Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
1 2 3 4
Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
1 2 3
Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
Say you have an array prices 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 (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
1 2 3 4
Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
1 2 3 4 5
Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
1 2 3
Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For a given n, a gray code sequence may not be uniquely defined. For example, [0,2,3,1] is also a valid gray code sequence.
00 - 0 10 - 2 11 - 3 01 - 1
Example 2:
1 2 3 4 5
Input: 0 Output: [0] Explanation: We define the gray code sequence to begin with 0. A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1. Therefore, for n = 0 the gray code sequence is [0].
1 2 3 4 5 6 7 8 9 10 11 12 13
// @lc code=start //公式 g(i) = i ^ (i / 2) import java.util.List; classSolution{ public List<Integer> grayCode(int n){ List<Integer> res = new ArrayList<>(); //0001左移两位变成0100 = 4,左移三位等于8 for (int i = 0; i < 1 << n; i++) { res.add(i ^ i >> 1);//除以2 } return res; } }
// @lc code=start classMinStack{ Stack<Integer> stack; int min;//Integer比较的是范围,是地址,Interger类型之间的比较应该用equals() /** initialize your data structure here. */ publicMinStack(){ stack = new Stack<>(); min = Integer.MAX_VALUE;//初始化Min } publicvoidpush(int x){ if (x <= min) { stack.push(min); min = x; } stack.push(x); } publicvoidpop(){ if (stack.pop() == min) { min = stack.pop(); } } publicinttop(){ return stack.peek(); } publicintgetMin(){ 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(); */ // @lc code=end
// class MinStack { // private Stack<Integer> stack; // private Stack<Integer> minStack; // /** initialize your data structure here. */ // public MinStack() { // stack = new Stack<>(); // minStack = new Stack<>(); // } // public void push(int x) { // stack.push(x); // if(!minStack.isEmpty()) { // int min = minStack.peek(); // if(x <= min) { // minStack.push(x); // } // } else { // minStack.push(x); // } // } // public void pop() { // int x = stack.pop(); // if(!minStack.isEmpty()) { // if(x == minStack.peek()) { // minStack.pop(); // } // } // } // public int top() { // return stack.peek(); // } // public int getMin() { // return minStack.peek(); // } // }
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
没有的注释的为O(1) /** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */
classMyQueue1{ Stack<Integer> s1; Stack<Integer> s2; /** Initialize your data structure here. */ publicMyQueue(){ s1 = new Stack(); s2 = new Stack(); } /** Push element x to the back of queue. */ publicvoidpush(int x){ s1.push(x); } //O(n) /** Removes the element from in front of queue and returns that element. */ publicintpop(){ //s1代表没进行过处理的,queue的反方向,则S2代表处理过的。 if(!s2.isEmpty()) return s2.pop(); else { while (!s1.isEmpty()) s2.push(s1.pop()); return s2.pop(); } } //O(n) /** Get the front element. */ publicintpeek(){ if(!s2.isEmpty()) return s2.peek(); else { while(!s1.isEmpty()) s2.push(s1.pop()); return s2.peek(); } } /** Returns whether the queue is empty. */ publicbooleanempty(){ return s1.isEmpty() && s2.isEmpty(); } }
//Methods 2 classMyQueue2{ Stack<Integer> s1; Stack<Integer> s2; privateint front; /** Initialize your data structure here. */ publicMyQueue(){ s1 = new Stack(); s2 = new Stack(); } /** Push element x to the back of queue. */ //O(n) publicvoidpush(int x){ if (s1.isEmpty()) { front = x; } while (!s1.isEmpty()) { s2.push(s1.pop()); } s2.push(x); while (!s2.isEmpty()) { s1.push(s2.pop()); } } /** Removes the element from in front of queue and returns that element. */ publicintpop(){ //s1代表没进行过处理的,queue的反方向,则S2代表处理过的。 int res = s1.pop(); if(!s1.isEmpty()) { front = s1.peek(); } return res; } /** Get the front element. */ publicintpeek(){ return front; } /** Returns whether the queue is empty. */ publicbooleanempty(){ return s1.isEmpty(); } }
You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
classMyStack{ //queue 4321 //stack 1234 /** Initialize your data structure here. */ Queue<Integer> queue; publicMyStack(){ //前后开口,所以一个queue就可以实现 queue = new LinkedList<>(); } /** Push element x onto stack. */ publicvoidpush(int x){ queue.add(x); for (int i = 0; i < queue.size() - 1; i++) { queue.add(queue.poll()); } } /** Removes the element on top of the stack and returns that element. */ publicintpop(){ return queue.poll(); } /** Get the top element. */ publicinttop(){ return queue.peek(); } /** Returns whether the stack is empty. */ publicbooleanempty(){ return queue.isEmpty(); } }
/** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */ // @lc code=end
The count-and-say sequence is the sequence of integers with the first five terms as following:
1 2 3 4 5
1. 1 2. 11 3. 21 4. 1211 5. 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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
1 2 3
Input: 1 Output: "1" Explanation: This is the base case.
Example 2:
1 2 3
Input: 4 Output: "1211" Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library’s sort function for this problem.
Example:
1 2
Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2]
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.
Could you come up with a one-pass algorithm using only constant space?
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
1 2 3 4 5
Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution{ publicvoidmerge(int[] nums1, int m, int[] nums2, int n){ int i = m - 1; int j = n - 1; int k = m + n - 1; while (i >= 0 && j >= 0) { //nums1和2都是排过序的,从后向前放,最大的放在最后 nums1[k--] = nums1[i] >= nums2[j] ? nums1[i--] : nums2[j--]; } while (j >= 0) { nums1[k--] = nums2[j--]; //i到极限,但是j还有剩余 } } }
Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
Example 1:
1 2 3 4 5 6
Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
1 2 3 4 5
Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
1 <= nums.length <= 2 * 10^4
It’s guaranteed that nums[i] fits in a 32 bit-signed integer.
Write a function that takes an unsigned integer and return the number of ‘1’ bits it has (also known as the Hamming weight).
Example 1:
1 2 3
Input: 00000000000000000000000000001011 Output: 3 Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
1 2 3
Input: 00000000000000000000000010000000 Output: 1 Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
1 2 3
Input: 11111111111111111111111111111101 Output: 31 Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
Note:
Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 3 above the input represents the signed integer -3.
Follow up:
If this function is called many times, how would you optimize it?
Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000 Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
1 2 3
Input: 11111111111111111111111111111101 Output: 10111111111111111111111111111111 Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
Note:
Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 2 above the input represents the signed integer -3 and the output represents the signed integer -1073741825.
Follow up:
If this function is called many times, how would you optimize it?
publicclassSolution{ // you need treat n as an unsigned value publicintreverseBits(int n){ if (n == 0) return0; int res = 0; for (int i = 0; i < 32; i++) { res <<= 1; //如果是偶数,为0,并且判断最低位是不是1 if ((n & 1) == 1) res++; // 1011 右移变成0101 n >>= 1; } return res; } }
Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example 1:
1 2 3 4 5
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
1 2 3 4 5 6 7
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
1 2 3 4 5 6 7 8
// nums is passed in by reference. (i.e., without making a copy) int len = removeElement(nums, val);
// any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); }
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.
Example 1:
1 2 3 4 5
Given 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 returned length.
Example 2:
1 2 3 4 5
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
1 2 3 4 5 6 7 8
// nums is passed in by reference. (i.e., without making a copy) int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); }
Given an input string, reverse the string word by word.
Example 1:
1 2
Input: "the sky is blue" Output: "blue is sky the"
Example 2:
1 2 3
Input: " hello world! " Output: "world! hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
1 2 3
Input: "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Note:
A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up:
For C programmers, try to solve it in-place in O(1) extra space.
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
classSolution{ public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> ans = new ArrayList(); int len = nums.length; if (nums == null || len < 3) return ans; Arrays.sort(nums);// 排序 for (int i = 0; i < len; i++) { if(nums[i] > 0) break;// 如果当前数字大于0,则三数之和一定大于0,所以结束循环 if (i > 0 && nums[i] == nums[i-1]) continue;// 去重 int L = i + 1; int R = len - 1; while (L < R) { int sum = nums[i] + nums[L] + nums[R]; if(sum == 0) { ans.add(Arrays.asList(nums[i], nums[L], nums[R])); while (L < R && nums[L] == nums[L+1]) L++;// 去重 while (L < R && nums[R] == nums[R-1]) R--;// 去重 L++; R--; } elseif (sum < 0) L++; elseif (sum > 0) R--; } } return ans; } }
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example 1:
1 2 3
Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
1 2 3 4 5 6 7 8
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
classSolution{ publicbooleansearchMatrix(int[][] matrix, int target){ if (matrix.length == 0 || matrix[0].length == 0) returnfalse; int row = matrix.length; int col = matrix[0].length; int start = 0; int end = row * col - 1;
while (start <= end) { int mid = start + (end - start) / 2; int value = matrix[mid / col][mid % col]; if (value == target) { returntrue; } elseif (value < target) { start = mid + 1; } else { end = mid - 1; } } returnfalse; } }
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.
classSolution{ publicintsearchInsert(int[] nums, int target){ int len = nums.length; if (len == 0) { return0; } if (nums[len - 1] < target) { return len; } int left = 0; int right = len - 1; while (left < right) { int mid = (left + right) >>> 1; // 严格小于 target 的元素一定不是解 if (nums[mid] < target) { left = mid + 1; } else { right = mid; } } return left; } }
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n\. You have to guess which number I picked.
Every time you guess wrong, I’ll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
1 2 3
-1 : My number is lower 1 : My number is higher 0 : Congrats! You got it!
Example :
1 2
Input: n = 10, pick = 6 Output: 6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicclassSolutionextendsGuessGame{ publicintguessNumber(int n){ int left = 1; int right = n; while (left < right) { int mid = (left + right + 1) >>> 1; int guessNum = guess(mid); if (guessNum == -1) { right = mid - 1;// 中位数比猜的数大,因此比中位数大的数包括中位数都不是目标元素 } else { left = mid; } } return left; } }
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.
Example:
1 2 3 4 5 6 7
Given n = 5, and version = 4 is the first bad version.
/* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */
publicclassSolutionextendsVersionControl{ publicintfirstBadVersion(int n){ int left = 1; int right = n; while (left < right) { int mid = left + (right - left) / 2; if(isBadVersion(mid)) { right = mid; } else { left = mid + 1; } } return left; } }
A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞.
Example 1:
1 2 3
Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
1 2 3 4
Input: nums = [1,2,1,3,5,6,4] Output: 1 or 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution{ publicintfindPeakElement(int[] nums){ int start = 0; int end = nums.length - 1; while (start <= end) { if (start == end) return start; int mid = start + (end - start) / 2; if(nums[mid] >= nums[mid + 1]) { end = mid; } else { start = mid + 1; } } return start; } }
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
1 2 3
Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
1 2 3
Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
1 2 3
Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
1 2 3
Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
1 2 3
Input: head = [1,2], pos = 0 Output: tail connects to node index 0 Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
1 2 3
Input: head = [1], pos = -1 Output: no cycle Explanation: There is no cycle in the linked list.
Follow-up: Can you solve it without using extra space?