Leetcode easy
1. Two Sum
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 等。
public class Solution {
public int[] twoSum(int[] nums, int target) {
int [] res = new int[2];
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
res[0] = i;
res[1] = j;
return res;
}
}
}
return res;
}
}
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<Integer,Integer>();
int [] res = new int[2];
for (int i = 0; i < nums.length; i++) {
if (hash.containsKey(target - nums[i])) {
res[0] = hash.get(target - nums[i]);
res[1] = i;
return res;
}
hash.put(nums[i], i);
}
return res;
}
}
6. ZigZag Conversion
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 : 索引范围没取好
按每行索引存储
public class Solution {
public String convert(String s, int numRows) {
if (s.length() < 3 || numRows == 1){
return s;
}
int cycle = 2 * numRows - 2;
StringBuffer res = new StringBuffer(s.length());
for (int i = 0; i < s.length(); i += cycle) {
res.append(s.charAt(i));
}
for (int i = 1; i < numRows - 1; i++) {
for (int j = i; j < s.length(); j+= cycle) {
res.append(s.charAt(j));
if (j + cycle - 2 * i < s.length()) {
res.append(s.charAt(j + cycle - 2 * i));
}
}
}
for (int i = numRows - 1; i < s.length(); i += cycle) {
res.append(s.charAt(i));
}
return res.toString();
}
}
先转成char数组更快
public class Solution {
public String convert(String s, int numRows) {
if (s.length() < 3 || numRows == 1){
return s;
}
char [] c = s.toCharArray();
int cycle = 2 * numRows - 2;
StringBuffer res = new StringBuffer(s.length());
for (int i = 0; i < s.length(); i += cycle) {
res.append(c[i]);
}
for (int i = 1; i < numRows - 1; i++) {
for (int j = i; j < s.length(); j+= cycle) {
res.append(c[j]);
if (j + cycle - 2 * i < s.length()) {
res.append(c[j + cycle - 2 * i]);
}
}
}
for (int i = numRows - 1; i < s.length(); i += cycle) {
res.append(c[i]);
}
return res.toString();
}
}
或按每列存储
public class Solution {
public String convert(String s, int nRows) {
char[] c = s.toCharArray();
int len = c.length;
StringBuffer[] sb = new StringBuffer[nRows];
for (int i = 0; i < sb.length; i++){
sb[i] = new StringBuffer();
}
int i = 0;
while (i < len) {
for (int idx = 0; idx < nRows && i < len; idx++){ // vertically down
sb[idx].append(c[i++]);
}
for (int idx = nRows - 2; idx >= 1 && i < len; idx--){ // obliquely up
sb[idx].append(c[i++]);
}
}
for (int idx = 1; idx < sb.length; idx++) {
sb[0].append(sb[idx]);
}
return sb[0].toString();
}
}
7. Reverse Integer
Reverse digits of an integer. Example1: x = 123, return 321
Example2: x = -123, return -321
注意溢出
public class Solution {
public int reverse(int x) {
long sum = 0;
while(x != 0){
sum = sum * 10 + x % 10;
x = x/10;
}
if(sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE)
return 0;
return (int)sum;
}
}
或者判断乘10后,再除10是否相等。
public class Solution {
/**
* @param n the integer to be reversed
* @return the reversed integer
*/
public int reverseInteger(int n) {
int reversed_n = 0; while (n != 0) {
int temp = reversed_n * 10 + n % 10;
n = n / 10;
if (temp / 10 != reversed_n) {
reversed_n = 0;
break;
}
reversed_n = temp;
}
return reversed_n;
}
}
8. String to Integer (atoi)
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, 溢出 空格 正负号等
public class Solution {
public int myAtoi(String str) {
if (str == null || str.length() == 0) {
return 0;
}
long sum = 0;
int i = 0;
int positive = 1;
while (str.charAt(i) == ' '){
i++;
}
if (str.charAt(i) == '+'){
i++;
} else if (str.charAt(i) == '-') {
i++;
positive = -1;
}
while (i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0') {
sum = sum * 10 + str.charAt(i) - '0';
i++;
if (sum > Integer.MAX_VALUE) {
return positive == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
}
return positive * (int) sum;
}
}
9. Palindrome Number -- No
Determine whether an integer is a palindrome. Do this without extra space.(回文数)
注意corner case 溢出,结尾为0,其余的回文,负数等。
2nd : 判断 结尾为0。
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || ( x !=0 && x % 10 == 0)) {
return false;
}
int rev = 0;
while (rev < x) {
rev = rev * 10 + x % 10;
x = x / 10;
}
return (x == rev || x == rev / 10);
}
}
day2: 注意return判断。
13. Roman to Integer
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from to .
按照规则,前缀的较小数减去即可。可通过map或子函数switch枚举建立映射
class Solution {
public:
int romanToInt(string s) {
if (s.empty()) return ;
map<char, int> p;
p['I'] = ; p['V'] = ; p['X'] = ;
p['L'] = ; p['C'] = ; p['D'] = ;
p['M'] = ;
int len = s.size();
int ans = p[s[len-]];
for (int i = len-; i >= ; i--) {
if (p[s[i]] < p[s[i+]]) {
ans -= p[s[i]];
} else {
ans += p[s[i]];
}
}
return ans;
}
};
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
思路: 1 从头到尾一个一个字节比较。
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
StringBuffer res = new StringBuffer();
for (int i = 0; i < strs[0].length(); i++) {
for (int j = 1; j < strs.length; j++) {
if (i >= strs[j].length() || strs[j].charAt(i) != strs[0].charAt(i)) {
return res.toString();
}
}
res.append(strs[0].charAt(i));
}
return res.toString();
}
}
2:前两个字符串求prefix,用此prefix与下一个str求prefix,递归。
public class Solution { public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String prefix = strs[0];
for(int i = 1; i < strs.length; i++) {
int j = 0;
while( j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j)) {
j++;
}
if( j == 0) {
return "";
}
prefix = prefix.substring(0, j);
}
return prefix;
} }
19. Remove Nth Node From End of List
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步即可。注意移除的是头指针这种情况。可从头指针前面加一个开始便利简化。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
while (n > 0 && fast != null) {
fast = fast.next;
n--;
}
if (fast == null) {
return head.next;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return head;
}
}
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode start = new ListNode(0);
ListNode slow = start, fast = start;
slow.next = head; //Move fast in front so that the gap between slow and fast becomes n
for(int i=1; i<=n+1; i++) {
fast = fast.next;
}
//Move fast to the end, maintaining the gap
while(fast != null) {
slow = slow.next;
fast = fast.next;
}
//Skip the desired node
slow.next = slow.next.next;
return start.next;
}
20. Valid Parentheses -- No Bug Free
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() &&
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case ')':
if (stack.empty() || stack.pop() != '(') {
return false;
}
break;
case ']':
if (stack.empty() || stack.pop() != '[') {
return false;
}
break;
case '}':
if (stack.empty() || stack.pop() != '{') {
return false;
}
break;
case '{':
case '[':
case '(':
stack.push(c);
break;
}
}
return stack.empty();
}
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
21. Merge Two Sorted Lists
合并两个有序链表。注意考虑两个链表是否会相交
/**
* 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
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.
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
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.
public class Solution {
public int removeElement(int[] nums, int val) {
int len = 0;
for (int num : nums) {
if (num != val) {
nums[len++] = num;
}
}
return len;
}
}
35. Search Insert Position
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.
[,,,], →
[,,,], →
[,,,], →
[,,,], →
题意:查找有序数组中第一个不小于target的下标。。(实现lower_bound)
1:O(n)线性。。。
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
/*if (nums == ull) {
return 0;
}*/
for (int i = ; i < nums.size(); i++) {
if (nums[i] >= target) {
return i;
}
}
return nums.size();
}
};
2 二分
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left =;
int mid=;
int right = nums.size()-;
if(nums.empty()) return ;
if(target>nums[nums.size()-]) return nums.size();
while(left<right){
mid = (left+right)/;
if(nums[mid]==target) return mid;
else if(nums[mid] > target) right = mid;
else left = mid + ;
}
return left;
}
};
36. Valid Sudoku --No Bug Free
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))(可通过画真值表枚举)
public class Solution {
public boolean isValidSudoku(char[][] board) {
for (int i = 0; i < 9; i++) {
HashSet<Character> row = new HashSet();
HashSet<Character> col = new HashSet();
HashSet<Character> cub = new HashSet();
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.' && !row.add(board[i][j])) {
return false;
}
if (board[j][i] != '.' && !col.add(board[j][i])) {
return false;
}
int rowIndex = 3 * (i / 3) + j /3;
int colIndex = 3 * (i % 3) + j % 3;
if (board[rowIndex][colIndex] != '.' && !cub.add(board[rowIndex][colIndex])) {
return false;
}
}
}
return true;
}
}
38. Count and Say
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.
暴力从同开始按规律生成即可.
public class Solution {
public String countAndSay(int n) {
StringBuffer res = new StringBuffer("1");
for (int k = 1; k < n; k++) {
StringBuffer temp = new StringBuffer();
for (int i = 0; i < res.length();) {
int j = 1;
while (i + j < res.length() && res.charAt(i) == res.charAt(i + j)) {
j++;
}
temp.append(j);
temp.append(res.charAt(i));
i += j;
}
res = temp;
}
return res.toString();
}
}
58. Length of Last Word
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.
思路:注意以" "结束的字符串即可。
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
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即可。
public class Solution {
public int[] plusOne(int[] digits) {
if (digits == null) {
return null;
}
int next = 0;
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i] ++;
break;
}
next = i -1;
digits[i] = 0;
}
if (next != -1) {
return digits;
}
int[] ans = new int [digits.length + 1];
ans[0] = 1;
for (int i = 1; i < ans.length; i++) {
ans[i] = digits[i - 1];
}
return ans;
}
}
优化:不满足直接return即可,最后不用复制,因为全是0。
public class Solution {
public int[] plusOne(int[] digits) {
int n = digits.length;
for(int i=n-1; i>=0; i--) {
if(digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] newNumber = new int [n+1];
newNumber[0] = 1;
return newNumber;
}
}
67. Add Binary --No
Given two binary strings, return their sum (also a binary string). For example,
a = "11"
b = "1"
Return "100".
可用 || 判断更为简洁。
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();
}
}
public class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1, j = b.length() -1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) sum += b.charAt(j--) - '0';
if (i >= 0) sum += a.charAt(i--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
}
69. Sqrt(x)
Implement int sqrt(int x). Compute and return the square root of x.
牛顿法
class Solution {
public:
int mySqrt(int x) {
long ans = x;
while (ans * ans > x) {
ans = (ans + x / ans) / ;
}
return ans;
}
};
70. Climbing Stairs
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), 注意空间复杂度。
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
Given a sorted linked list, delete all duplicates such that each element appear only once. For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3
思路:比较与前一个是否相同即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
ListNode cur = head.next;
ListNode prev = head;
while (cur != null) {
if (cur.val == prev.val) {
prev.next = cur.next;
cur = cur.next;
} else {
prev = cur;
cur = cur.next;
}
}
return head;
}
}
88. Merge Sorted Array --No
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.
不要从前往后,从后往前即可。
public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int index = m - 1;
int index2 = n - 1;
int cur = m + n - 1;
while (index >= 0 && index2 >= 0) {
if (nums2[index2] >= nums1[index]) {
nums1[cur--] = nums2[index2--];
} else {
nums1[cur--] = nums1[index--];
}
}
while (index2 >= 0) {
nums1[cur--] = nums2[index2--];
}
}
}
100. Same Tree
Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value
递归比较即可,可尝试用非递归。
/**
* 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 isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) {
return p == q;
}
return p.val == q.val && isSameTree(p.left, q.left)
&& isSameTree(p.right, q.right);
}
}
101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
思路:初级递归。
/**
* 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 isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isSymmetric(root.left, root.right);
}
private boolean isSymmetric(TreeNode node1, TreeNode node2) {
if (node1 == null || node2 == null) {
return node1 == node2;
}
return node1.val == node2.val && isSymmetric(node1.left, node2.right)
&& isSymmetric(node1.right, node2.left);
}
}
102. Binary Tree Level Order Traversal --No
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
思路:队列BFS或递归DFS
1st: 注意变量名。
/**
* 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;
}
}
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
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即可。
/**
* 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;
}
}
/**
* 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
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). For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
BFS时每次加到前面即可。
/**
* 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>> levelOrderBottom(TreeNode root) {
LinkedList<List<Integer>> ans = new LinkedList();
if (root == null) {
return ans;
}
Queue<TreeNode> cur = new LinkedList();
cur.add(root);
while (!cur.isEmpty()) {
int num = cur.size();
List<Integer> temp = new ArrayList(num);
for (int i = 0; i < num; i++) {
TreeNode node = cur.poll();
temp.add(node.val);
if (node.left != null){
cur.add(node.left);
}
if (node.right != null) {
cur.add(node.right);
}
}
ans.addFirst(temp);
}
return ans;
}
}
108. Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
递归处理即可。
/**
* 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, , nums.size() - );
}
TreeNode* sortedArrayToBST(vector<int>& nums, int start, int end) {
if (start > end) {
return nullptr;
}
int mid = (start + end) / ;
TreeNode* ret = new TreeNode(nums[mid]);
ret->left = sortedArrayToBST(nums, start, mid - );
ret->right = sortedArrayToBST(nums, mid + , end);
return ret;
}
};
110. Balanced Binary Tree --No
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则不平衡)。
/**
* 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));
}
}
}
/**
* 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
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完。
/**
* 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。
/**
* 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
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了后面还能补回来,不能提前结束)。
/**
* 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
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,可从第一层迭代。
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;
}
}
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
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.
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
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.
public class Solution {
public int maxProfit(int[] prices) {
int total = ;
for (int i=; i< prices.length-; i++) {
if (prices[i+]>prices[i]) total += prices[i+]-prices[i];
} return total;
}
若是第二种,可用优先级队列(盈利就卖同时假设买入即可)
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> prices(n);
for (int i = ; i < n; i++) {
cin >> prices[i];
}
priority_queue<int, vector<int>, greater<int> > q;
int ans = ;
for (int price : prices) {
while (!q.empty() && price > q.top()) {
ans += price - q.top();
q.pop();
q.push(price);
}
q.push(price);
}
cout << ans << "\n";
}
更简单的办法:从后往前扫,记录当前时刻股票能卖的最高价即可。 sell[n-1] = max(sell[n], a[n])
125. Valid Palindrome
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.
思路:双指针判断头和尾是否相等即可,注意不区分大小写和无视非数字字母。
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
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?
异或即可。
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
Given a linked list, determine if it has a cycle in it. Follow up:
Can you solve it without using extra space?
快慢指针。
1st:注意条件判断。
/**
* 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
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).
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。
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
Compare two version numbers version1 and version2.
If version1 > version2 return , if version1 < version2 return -, otherwise return . 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:分别求小数点前后的数,然后比较。
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)
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
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={, , , }, target=
Output: index1=, index2=
双指针分别从0, n-1往中间夹逼即可。
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int lo = , hi = numbers.size()-;
while (lo < hi) {
int sub = target - numbers[lo]-numbers[hi];
if (sub==) {
break;
} else if (sub < ) {
hi--;
} else {
lo++;
}
}
return vector<int>{lo+, hi+};
}
};
168. Excel Sheet Column Title -- No
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进制,注意从一开始,所以每次计算减一。
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
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。(若不一定存在,则需在遍历一遍计算出现次数)。
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
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类似即可。
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
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
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循环注意溢出)
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。无溢出。
public class Solution {
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n = n / 5;
count += n;
}
return count;
}
}
或者 递归。
public class Solution {
public int trailingZeroes(int n) {
if ( n == 0) {
return 0;
}
return n / 5 + trailingZeroes( n / 5);
}
}
189. Rotate Array --No
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),终止条件:计算更新次数
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取余。
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
Reverse bits of a given bits unsigned integer. For example, given input (represented in binary as ), return (represented in binary as ). Follow up:
If this function is called many times, how would you optimize it? Related problem: Reverse Integer
思路:一直移位求最后一位然后累积即可,注意为unsigned,要用位操作,不能够*。
1st: 循环够32次, << & 优先级比 + 低。
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
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.
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或重合停止.
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))
class Solution {
public:
int countPrimes(int n) {
vector<bool> prime(n, true);
int cnt = ;
for (int i = ; i < n; i++) {
if (prime[i]) {
cnt++;
for (int j = ; j*i < n; j++) {
prime[j*i] = false;
}
}
}
return cnt;
}
};
2 线性欧拉筛O(n)
int findPrime1(int n) {
vector<bool> prime(n + , true);
vector<int> primeList(n+); int primeCount = ;
for (int i = ; i <= n; i++) {
if (prime[i]) {
primeCount++;
primeList[primeCount] = i;
}
for (int j = ; j <= primeCount; j++) {
if (i*primeList[j] > n) break;
prime[i*primeList[j]] = false;
if (i%primeList[j] == ) break;
}
}
return primeCount;
}
278. First Bad Version
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 [, , ..., 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
// Forward declaration of isBadVersion API.
bool isBadVersion(int version); class Solution {
public:
int firstBadVersion(int n) {
int lo = , hi = n;
while (lo < hi) {
int mid = lo + (hi-lo)/;
if (isBadVersion(mid)) {
hi = mid;
} else {
lo = mid + ;
}
}
return lo;
}
};
2 lo <= hi hi = mid-1 or li = mid+1 , 最后 hi = lo -1
bool isBadVersion(int version); class Solution {
public:
int firstBadVersion(int n) {
int lo = , hi = n;
while (lo <= hi) {
int mid = lo + (hi-lo)/;
if (isBadVersion(mid)) {
hi = mid-;
} else {
lo = mid + ;
}
}
return lo;
}
};
283. Move Zeroes
given an array nums, write a function to move all 's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [, , , , ], after calling your function, nums should be [, , , , ]. Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
利用指针,非0元素填充,之后的全为0即可。
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int index = ;
int n = nums.size();
for (int i = ; i < n; i++) {
if (nums[i] != ) {
nums[index++] = nums[i];
}
}
for (; index < n; index++) {
nums[index] = ;
}
}
};
461. Hamming Distance
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.
class Solution {
public:
int hammingDistance(int x, int y) {
int ans = ;
while (x || y) {
ans += (x&) ^ (y&);
x >>=;
y >>= ;
}
return ans;
}
};
按位比较即可,或者先异或。
class Solution {
public:
int hammingDistance(int x, int y) {
int ans = ;
while (x || y) {
ans += (x&) ^ (y&);
x >>=;
y >>= ;
}
return ans;
}
};
class Solution {
public:
int hammingDistance(int x, int y) {
int ans = ;
int xy = x ^ y;
while (xy) {
ans += xy&;
xy >>=;
}
return ans;
}
};
476. Number Complement --No
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 -bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.
Example :
Input:
Output:
Explanation: The binary representation of is (no leading zero bits), and its complement is . So you need to output .
Example :
Input:
Output:
Explanation: The binary representation of is (no leading zero bits), and its complement is . So you need to output
按位操作即可。
class Solution {
public:
int findComplement(int num) {
int ans = ;
int i = ;
while (num) {
//ans += (!(num&1)) << i; !!!!
if ((num&) == ) {
ans += << i;
}
i++;
num >>= ;
}
return ans;
}
};
class Solution {
public:
int findComplement(int num) {
unsigned mask = ~;
while (num&mask) {
mask <<=;
}
return ~mask & ~num; // ~(mask|| num) !!!!
}
};
561. Array Partition I --2 No
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 to n as large as possible. Example :
Input: [,,,] Output:
Explanation: n is , and the maximum sum of pairs is = min(, ) + min(, ).
Note:
n is a positive integer, which is in the range of [, ].
All the integers in the array will be in the range of [-, ].
1 排序取偶数位 O(nlgn)
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
int res = ;
sort(nums.begin(),nums.end());
for(int i =; i<nums.size(); i+=){
res += nums[i];
}
return res;
}
};
2 空间换时间 vector统计出现次数。 注意
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
vector<int> hash();
for (int num : nums) {
hash[num+]++;
}
bool even = true;
int ans = ;
for (int i = ; i < ; i++) {
if (hash[i]) {
ans += (i - ) * (hash[i] / );
if (hash[i] % ) {
ans += even ? (i - ) : ;
even = !even;
}
}
}
return ans;
}
};
575. Distribute Candies
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 :
Input: candies = [,,,,,]
Output:
Explanation:
There are three different kinds of candies (, and ), and two candies for each kind.
Optimal distribution: The sister has candies [,,] and the brother has candies [,,], too.
The sister has three different kinds of candies.
Example :
Input: candies = [,,,]
Output:
Explanation: For example, the sister has candies [,] and the brother has candies [,].
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 [, ,], and will be even.
The number in given array is in range [-,, ,].
用set或bitset数组统计出现种类数即可。
class Solution {
public:
int distributeCandies(vector<int>& candies) {
vector<bool> hash(, false);
int cnt = ;
for (int candy : candies) {
if (!hash[candy+]) {
cnt++;
hash[candy+] = true;
if (cnt == candies.size()/) {
return cnt;
}
}
}
return cnt;
}
};
617. Merge Two Binary Trees
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 :
Input:
Tree Tree / \ / \ / \ \ Output:
Merged tree: / \ / \ \ Note: The merging process must start from the root nodes of both trees.
递归即可。
/**
* 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
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most element. We define an array is non-decreasing if array[i] <= array[i + ] holds for every i ( <= i < n). Example :
Input: [,,]
Output: True
Explanation: You could modify the first to to get a non-decreasing array.
Example :
Input: [,,]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.
Note: The n belongs to [, ,].
遍历即可,找到第一个下降点nums[i] < nums[i-1], 此时有两种选择:升高nums[i] 或降低nums[i-1], 由于应让nums[i]尽可能小, 所以优先降低nums[i-1]。(由于最多降到nums[i-2],所以nums[i-2]应<=nums[i])。
class Solution {
public:
bool checkPossibility(vector<int>& nums) {
int n = nums.size();
bool modify = false;
for (int i = ; i < n; i++) {
if (nums[i] < nums[i-]) {
if (modify)
return false;
if (i != && nums[i-] > nums[i]) {
nums[i] = nums[i-];
} else {
nums[i-] = nums[i];
}
modify = true;
}
}
return true;
}
};
657. Judge Route Circle
Initially, there is a Robot at position (, ). 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.
class Solution {
public:
bool judgeCircle(string moves) {
int u = , r = ;
for (char c : moves) {
if (c == 'U') {
u++;
} else if (c == 'D') {
u--;
} else if (c == 'R') {
r++;
} else {
r--;
}
}
return u== && r==;
}
};
Leetcode easy的更多相关文章
- leetcode easy problem set
*勿以浮沙筑高台* 持续更新........ 题目网址:https://leetcode.com/problemset/all/?difficulty=Easy 1. Two Sum [4m ...
- 决战Leetcode: easy part(51-96)
本博客是个人原创的针对leetcode上的problem的解法,所有solution都基本通过了leetcode的官方Judging,个别未通过的例外情况会在相应部分作特别说明. 欢迎互相交流! em ...
- 决战Leetcode: easy part(1-50)
本博客是个人原创的针对leetcode上的problem的解法,所有solution都基本通过了leetcode的官方Judging,个别未通过的例外情况会在相应部分作特别说明. 欢迎互相交流! em ...
- [Leetcode easy]存些水题34、20、700
leetcode 34 最早出现和最后出现 class Solution { public int[] searchRange(int[] nums, int target) { int []ans= ...
- LeetCode(Easy)--C++笔记
前言:这是关于LeetCode上面练习题C++的笔记,有些地方参考有网友的解题方法(可能有些参考没能注明,望谅解),如有需要改进的地方希望留言指教,多谢! 目录: ZigZag Conversion ...
- C# 写 LeetCode easy #14 Longest Common Prefix
14.Longest Common Prefix Write a function to find the longest common prefix string amongst an array ...
- C# 写 LeetCode easy #28 Implement strStr()
28.Implement strStr() Implement strStr(). Return the index of the first occurrence of needle in hays ...
- C# 写 LeetCode easy #27 Remove Element
27. Remove Element Given an array nums and a value val, remove all instances of that value in-place ...
- C# 写 LeetCode easy #26 Remove Duplicates from Sorted Array
26.Remove Duplicates from Sorted Array Given a sorted array nums, remove the duplicates in-place suc ...
随机推荐
- 云优化的概念、Entity Framework 7.0、简单吞吐量压力测试
云优化的概念.Entity Framework 7.0.简单吞吐量压力测试 继续上一篇<开发 ASP.NET vNext 初步总结(使用Visual Studio 2014 CTP1)>之 ...
- The Decoder - UVa458
欢迎访问我的新博客:http://www.milkcu.com/blog/ 原文地址:http://www.milkcu.com/blog/archives/uva458.html 题目描述 The ...
- Apache HttpServer Installing the apache2.2 service <OS 5>拒绝访问. :Failed to open the WinNT service manager
Installing the apache2.2 service<OS 5>拒绝访问. :Failed to open the WinNT service manager 只需要于管理员 ...
- 红黑树LLRB
LLRB——红黑树的现代实现 一.本文内容 以一种简明易懂的方式介绍红黑树背后的逻辑实现2-3-4树,以及红黑树的插入.删除操作,重点在2-3-4树与红黑树的对应关系上,并理清红黑树相关操作的来龙去脉 ...
- 长度为n的数组,有一个数重复出现了n/2+1次,找出(三种方法)
问题: 长度为n的数组,有一个数重复出现了n/2+1次,找出这个数: 解决: 比较直接的思路是遍历每个元素,让其与剩下其他元素比较,相等一次计数器sum++,直到sum=n/2+1为止: #inc ...
- CKeditor 集成 CKFinder
之前照着网上的做,遇到了一些问题,经过多次实验修改最后算是成功了,下面进行详细讲解. 一.CKeditor的配置(附件中已有最新版CKeditor和CKFinder) 1.需要下载ckeditor, ...
- weblogic配置修改java代码后不需要重启热部署方式
我用的是weblogic8.x 在项目的WEB-INFO中创建weblogic.xml --------以下内容复制到weblogic.xml中------------ <!DOCTYPE we ...
- Alfred工具
神兵利器——Alfred 有人的地方就有江湖,有江湖就有纷争. 很多人说我的文字风格相对轻松和温和,那是因为我很早就认识到,我们没有教育脑残和喷子的义务.在网际多年,看过太多虚拟的刀锋和鲜血,很多人被 ...
- win7 安装 sql2000
win7 安装:http://wenku.baidu.com/link?url=xNcfrMaMzX0KgBcjpMaySRaKITM2Op73ZI8sOX49zgl-GWPGB3vqye9gZA_c ...
- python 调用 bash (python 调用linux命令)
原文这里有显示地址:http://zhou123.blog.51cto.com/4355617/1312791 现在摘取一部分: 这里介绍一下python执行shell命令的四种方法: 1.os模块中 ...