├── README.md ├── 344-Reverse-String.cpp ├── 371-Sum-of-Two-Integers.cpp ├── 136-Single-Number.cpp ├── 326-Power-of-Three.cpp ├── 231-Power-of-Two.cpp ├── 217-Contains-Duplicate.cpp ├── 258-Add-Digits.cpp ├── 191-Number-of-1-Bits.cpp ├── 069-Sqrt(x).cpp ├── 053-Maximum-Subarray.cpp ├── 171-Excel-Sheet-Column-Number.cpp ├── 237-Delete-Node-in-a-Linked-List.cpp ├── 268-Missing-Number.cpp ├── 169-Majority-Element.cpp ├── 292-Nim-Game.cpp ├── 504-Base-7.cpp ├── 122-Best-Time-to-Buy-and-Sell-Stock-II.cpp ├── 561-Array-Partition-I.cpp ├── 206-Reverse-Linked-List.cpp ├── 387-First-Unique-Character-in-a-String.cpp ├── 453-Minimum-Moves-to-Equal-Array-Elements.cpp ├── 485-Max-Consecutive-Ones.cpp ├── 349-Intersection-of-Two-Arrays.cpp ├── 001-Two-Sum.cpp ├── 058-Length-of-Last-Word.java ├── 013-Roman-to-Integer.cpp ├── 027-Remove-Element.cpp ├── 283-Move-Zeroes.cpp ├── 083-Remove-Duplicates-from-Sorted-List.java ├── 100-Same-Tree.cpp ├── 104-Maximum-Depth-Of-Binary-Tree.cpp ├── 094-Binary-Tree-Inorder-Traversal.java ├── 242-Valid-Anagram.cpp ├── 021-Merge-Two-Sorted-Lists.cpp ├── 476-Number-Complement.cpp ├── 009-Palindrome-Number.cpp ├── 448-Find-All-Numbers-Disappeared-in-an-Array.cpp ├── 026-Remove-Duplicates-from-Sorted-Array.cpp ├── 541-Reverse-String-II.cpp ├── 121-Best-Time-to-Buy-and-Sell-Stock.cpp ├── 551-Student-Attendance-Record-I.cpp ├── 461-Hamming-Distance.cpp ├── 066-Plus-One.java ├── 404-Sum-of-Left-Leaves.cpp ├── 226-Invert-Binary-Tree.cpp ├── 167-Two-Sum-II-Input-array-is-sorted.cpp ├── 035-Search-Insert-Position.java ├── 557-Reverse-Words-in-a-String-III.cpp ├── 507-Perfect-Number.java ├── 011-Container-With-Most-Water.cpp ├── 292-Nim-Game.java ├── 383-Ransom-Note.cpp ├── 088-Merge-Sorted-Array.java ├── 006-ZigZag-Conversion.cpp ├── 447-Number-of-Boomerangs.cpp ├── 350-Intersection-of-Two-Arrays-II.cpp ├── 409-Longest-Palindrome.cpp ├── 038-Count-and-Say.cpp ├── 530-Minimum-Absolute-Difference-in-BST.cpp ├── 492-Construct-the-Rectangle.cpp ├── 238-Product-of-Array-Except-Self.java ├── 412-Fizz-Buzz.cpp ├── 414-Third-Maximum-Number.cpp ├── 463-Island-Perimeter.cpp ├── 598-Range-Addition-II.cpp ├── 034-Search-for-a-Range.java ├── 521-Longest-Uncommon-Subsequence-I.cpp ├── 500-Keyboard-Row.cpp ├── 520-Detect-Capital.cpp ├── 563-Binary-Tree-Tilt.cpp ├── 543-Diameter-of-Binary-Tree.cpp ├── 002-Add-Two-Numbers.cpp ├── 401-Binary-Watch.cpp ├── 123-Best-Time-to-Buy-and-Sell-Stock-III.java ├── 669-Trim-a-Binary-Search-Tree.java ├── 575-Distribute-Candies.cpp ├── 328-Odd-Even-Linked-List.java ├── 459-Repeated-Substring-Pattern.java ├── 455-Assign-Cookies.cpp ├── 116-Populating-Next-Right-Pointers-in-Each-Node.java ├── 617-Merge-Two-Binary-Trees.cpp ├── 415-Add-Strings.cpp ├── 075-Sort-Colors.java ├── 054-Spiral-Matrix.java ├── 566-Reshape-the-Matrix.cpp ├── 532-K-diff-Pairs-in-an-Array.java ├── 059-Spiral-Matrix-II.java ├── 599-Minimum-Index-Sum-of-Two-Lists.cpp ├── 523-Continuous-Subarray-Sum.java ├── 537-Complex-Number-Multiplication.cpp ├── 067-Add-Binary.java ├── 008-String-to-Integer(atoi).cpp ├── 007-Reverse-Integer.cpp └── 682-Baseball-Game.java /README.md: -------------------------------------------------------------------------------- 1 | # 简介 2 | 本页面将持续更新 LeetCode 的题解。 3 | 4 | # 推广 5 | 您同时可浏览我的个人博客查看相关内容:http://chenhy.com/tags/leetcode/ 6 | 7 | 8 | -------------------------------------------------------------------------------- /344-Reverse-String.cpp: -------------------------------------------------------------------------------- 1 | 344. Reverse String 2 | 3 | Write a function that takes a string as input and returns the string reversed. 4 | 5 | Example: 6 | Given s = "hello", return "olleh". 7 | 8 | 9 | 10 | 11 | class Solution { 12 | public: 13 | string reverseString(string s) { 14 | reverse(s.begin(),s.end()); 15 | return s; 16 | } 17 | }; -------------------------------------------------------------------------------- /371-Sum-of-Two-Integers.cpp: -------------------------------------------------------------------------------- 1 | 371. Sum of Two Integers 2 | 3 | Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 4 | 5 | Example: 6 | Given a = 1 and b = 2, return 3. 7 | 8 | Credits: 9 | Special thanks to @fujiaozhu for adding this problem and creating all test cases. 10 | 11 | 12 | 13 | 14 | 15 | class Solution { 16 | public: 17 | int getSum(int a, int b) { 18 | return b==0?a:getSum(a^b,(a&b)<<1); 19 | } 20 | }; -------------------------------------------------------------------------------- /136-Single-Number.cpp: -------------------------------------------------------------------------------- 1 | 136. Single Number 2 | 3 | Given an array of integers, every element appears twice except for one. Find that single one. 4 | 5 | Note: 6 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 7 | 8 | 9 | 10 | 11 | 12 | 13 | class Solution { 14 | public: 15 | int singleNumber(vector& nums) { 16 | int ret = 0; 17 | for(int num:nums){ 18 | ret^=num; 19 | } 20 | return ret; 21 | } 22 | }; -------------------------------------------------------------------------------- /326-Power-of-Three.cpp: -------------------------------------------------------------------------------- 1 | 326. Power of Three 2 | 3 | Given an integer, write a function to determine if it is a power of three. 4 | 5 | Follow up: 6 | Could you do it without using any loop / recursion? 7 | 8 | 9 | 10 | 11 | class Solution { 12 | public: 13 | bool isPowerOfThree(int n) { 14 | if(n<=0){ 15 | return false; 16 | } 17 | while(n%3==0){ 18 | n/=3; 19 | } 20 | if(n==1){ 21 | return true; 22 | } 23 | return false; 24 | } 25 | }; -------------------------------------------------------------------------------- /231-Power-of-Two.cpp: -------------------------------------------------------------------------------- 1 | 231. Power of Two 2 | 3 | Given an integer, write a function to determine if it is a power of two. 4 | 5 | 6 | 7 | class Solution { 8 | public: 9 | bool isPowerOfTwo(int n) { 10 | int flag=0; 11 | if(n<=0){ 12 | return false; 13 | } 14 | while(n>0){ 15 | if(n&1==1){ 16 | if(flag==1){ 17 | return false; 18 | } 19 | flag=1; 20 | } 21 | n=n>>1; 22 | } 23 | return true; 24 | } 25 | }; -------------------------------------------------------------------------------- /217-Contains-Duplicate.cpp: -------------------------------------------------------------------------------- 1 | 217. Contains Duplicate 2 | 3 | Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 4 | 5 | 6 | 7 | 8 | class Solution { 9 | public: 10 | bool containsDuplicate(vector& nums) { 11 | unordered_set set; 12 | for(int num:nums){ 13 | if(set.count(num)){ 14 | return true; 15 | } 16 | set.insert(num); 17 | } 18 | return false; 19 | } 20 | }; -------------------------------------------------------------------------------- /258-Add-Digits.cpp: -------------------------------------------------------------------------------- 1 | 258. Add Digits 2 | 3 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 4 | 5 | For example: 6 | 7 | Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 8 | 9 | Follow up: 10 | Could you do it without any loop/recursion in O(1) runtime? 11 | 12 | Credits: 13 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 14 | 15 | 16 | 17 | 18 | 19 | class Solution { 20 | public: 21 | int addDigits(int num) { 22 | return 1+(num-1)%9; 23 | } 24 | }; -------------------------------------------------------------------------------- /191-Number-of-1-Bits.cpp: -------------------------------------------------------------------------------- 1 | 191. Number of 1 Bits 2 | 3 | Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 4 | 5 | For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 6 | 7 | Credits: 8 | 9 | 10 | 11 | 12 | 13 | 14 | class Solution { 15 | public: 16 | int hammingWeight(uint32_t n) { 17 | int sum=0; 18 | while(n>0){ 19 | if(n&1==1){ 20 | sum++; 21 | } 22 | n=n>>1; 23 | } 24 | return sum; 25 | } 26 | }; -------------------------------------------------------------------------------- /069-Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | 69. Sqrt(x) 2 | 3 | Implement int sqrt(int x). 4 | 5 | Compute and return the square root of x. 6 | 7 | 8 | 9 | 10 | 11 | 12 | class Solution { 13 | public: 14 | int mySqrt(int x) { 15 | if(x==0){ 16 | return 0; 17 | } 18 | int low=1,high=x; 19 | int mid; 20 | while(1){ 21 | mid = (low+high)/2; 22 | if(mid>x/mid){ 23 | high = mid-1; 24 | } 25 | else{ 26 | if((mid+1)>(x/(mid+1))){ 27 | return mid; 28 | } 29 | low = mid+1; 30 | } 31 | } 32 | } 33 | }; -------------------------------------------------------------------------------- /053-Maximum-Subarray.cpp: -------------------------------------------------------------------------------- 1 | 53. Maximum Subarray 2 | 3 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 4 | 5 | For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 6 | the contiguous subarray [4,-1,2,1] has the largest sum = 6. 7 | 8 | click to show more practice. 9 | 10 | Subscribe to see which companies asked this question. 11 | 12 | 13 | 14 | 15 | int maxSubArray(int* nums, int numsSize) { 16 | int sum=0; 17 | int max=INT_MIN; 18 | for(int i=0;imax){ 21 | max = sum; 22 | } 23 | if(sum<0){ 24 | sum = 0; 25 | } 26 | } 27 | return max; 28 | } -------------------------------------------------------------------------------- /171-Excel-Sheet-Column-Number.cpp: -------------------------------------------------------------------------------- 1 | 171. Excel Sheet Column Number 2 | 3 | Related to question Excel Sheet Column Title 4 | 5 | Given a column title as appear in an Excel sheet, return its corresponding column number. 6 | 7 | For example: 8 | 9 | A -> 1 10 | B -> 2 11 | C -> 3 12 | ... 13 | Z -> 26 14 | AA -> 27 15 | AB -> 28 16 | Credits: 17 | Special thanks to @ts for adding this problem and creating all test cases. 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | class Solution { 28 | public: 29 | int titleToNumber(string s) { 30 | int sum=0; 31 | for(int i=0;i 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 6 | 7 | 8 | 9 | 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode(int x) : val(x), next(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | void deleteNode(ListNode* node) { 22 | auto next = node->next; 23 | *node = *next; 24 | delete next; 25 | } 26 | }; -------------------------------------------------------------------------------- /268-Missing-Number.cpp: -------------------------------------------------------------------------------- 1 | 268. Missing Number 2 | 3 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 4 | 5 | For example, 6 | Given nums = [0, 1, 3] return 2. 7 | 8 | Note: 9 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 10 | 11 | 12 | 13 | 14 | 15 | 16 | class Solution { 17 | public: 18 | int missingNumber(vector& nums) { 19 | int sum=0; 20 | int realsum=0; 21 | bool flag=false; 22 | for(int i=0;i& nums) { 15 | int major=nums[0]; 16 | int cnt=1; 17 | for(int num:nums){ 18 | if(num==major){ 19 | ++cnt; 20 | }else{ 21 | --cnt; 22 | } 23 | if(cnt==0){ 24 | ++cnt; 25 | major = num; 26 | } 27 | } 28 | return major; 29 | } 30 | }; -------------------------------------------------------------------------------- /292-Nim-Game.cpp: -------------------------------------------------------------------------------- 1 | 292. Nim Game 2 | 3 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 4 | 5 | Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 6 | 7 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 8 | 9 | 10 | 11 | 12 | 13 | class Solution { 14 | public: 15 | bool canWinNim(int n) { 16 | return n%4; 17 | } 18 | }; -------------------------------------------------------------------------------- /504-Base-7.cpp: -------------------------------------------------------------------------------- 1 | 504. Base 7 2 | 3 | Given an integer, return its base 7 string representation. 4 | 5 | Example 1: 6 | Input: 100 7 | Output: "202" 8 | Example 2: 9 | Input: -7 10 | Output: "-10" 11 | Note: The input will be in range of [-1e7, 1e7]. 12 | 13 | 14 | 15 | 16 | 17 | 18 | class Solution { 19 | public: 20 | string convertToBase7(int num) { 21 | string str=""; 22 | int nega=0; 23 | if(num<0){ 24 | nega = 1; 25 | num = abs(num); 26 | } 27 | while(num/7){ 28 | str+=to_string(num%7); 29 | num/=7; 30 | } 31 | str+=to_string(num%7); 32 | if(nega){ 33 | str+="-"; 34 | } 35 | reverse(str.begin(),str.end()); 36 | return str; 37 | } 38 | }; -------------------------------------------------------------------------------- /122-Best-Time-to-Buy-and-Sell-Stock-II.cpp: -------------------------------------------------------------------------------- 1 | 122. Best Time to Buy and Sell Stock II 2 | 3 | Say you have an array for which the ith element is the price of a given stock on day i. 4 | 5 | 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). 6 | 7 | 8 | 9 | 10 | 11 | 12 | class Solution { 13 | public: 14 | int maxProfit(vector& prices) { 15 | int profit=0; 16 | for(int i=1;i& nums) { 21 | int sum=0; 22 | sort(nums.begin(),nums.end()); 23 | for(int i=0;inext; 28 | if(pNext==nullptr){ 29 | pRet=pNode; 30 | } 31 | pNode->next=pPre; 32 | pPre=pNode; 33 | pNode=pNext; 34 | } 35 | return pRet; 36 | } 37 | }; -------------------------------------------------------------------------------- /387-First-Unique-Character-in-a-String.cpp: -------------------------------------------------------------------------------- 1 | 387. First Unique Character in a String 2 | 3 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 4 | 5 | Examples: 6 | 7 | s = "leetcode" 8 | return 0. 9 | 10 | s = "loveleetcode", 11 | return 2. 12 | Note: You may assume the string contain only lowercase letters. 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | class Solution { 21 | public: 22 | int firstUniqChar(string s) { 23 | int arr[26]; 24 | for(int i=0;i<26;++i){ 25 | arr[i]=0; 26 | } 27 | for(int i=0;i [2,3,3] => [3,4,3] => [4,4,4] 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | class Solution { 25 | public: 26 | int minMoves(vector& nums) { 27 | int min=INT_MAX; 28 | int sum=0; 29 | for(int num:nums){ 30 | min=min& nums) { 23 | int cnt=0,max=0; 24 | for(int num:nums){ 25 | if(num==1){ 26 | cnt++; 27 | }else{ 28 | cnt=0; 29 | } 30 | max = max>cnt?max:cnt; 31 | } 32 | return max; 33 | } 34 | }; -------------------------------------------------------------------------------- /349-Intersection-of-Two-Arrays.cpp: -------------------------------------------------------------------------------- 1 | 349. Intersection of Two Arrays 2 | 3 | Given two arrays, write a function to compute their intersection. 4 | 5 | Example: 6 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 7 | 8 | Note: 9 | Each element in the result must be unique. 10 | The result can be in any order. 11 | 12 | 13 | 14 | 15 | 16 | class Solution { 17 | public: 18 | vector intersection(vector& nums1, vector& nums2) { 19 | unordered_set s; 20 | vector ret; 21 | 22 | for(int num1:nums1){ 23 | if(s.count(num1)==0){ 24 | s.insert(num1); 25 | } 26 | } 27 | for(int num2:nums2){ 28 | if(s.count(num2)){ 29 | ret.push_back(num2); 30 | s.erase(num2); 31 | } 32 | } 33 | return ret; 34 | } 35 | }; -------------------------------------------------------------------------------- /001-Two-Sum.cpp: -------------------------------------------------------------------------------- 1 | 1. Two Sum 2 | 3 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 4 | 5 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 6 | 7 | Example: 8 | Given nums = [2, 7, 11, 15], target = 9, 9 | 10 | Because nums[0] + nums[1] = 2 + 7 = 9, 11 | return [0, 1]. 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | class Solution { 20 | public: 21 | vector twoSum(vector& nums, int target) { 22 | unordered_map hm; 23 | for(int i=0;i(nums[i],i)); 25 | } 26 | 27 | for(int i=0;i=0&&s.charAt(i)==' '){ 28 | i--; 29 | } 30 | while(i>=0&&s.charAt(i)!=' '){ 31 | i--; 32 | count++; 33 | } 34 | 35 | return count; 36 | } 37 | } -------------------------------------------------------------------------------- /013-Roman-to-Integer.cpp: -------------------------------------------------------------------------------- 1 | 13. Roman to Integer 2 | 3 | Given a roman numeral, convert it to an integer. 4 | 5 | Input is guaranteed to be within the range from 1 to 3999. 6 | 7 | 8 | 9 | 10 | 11 | class Solution { 12 | public: 13 | int romanToInt(string s) { 14 | unordered_map hm; 15 | hm.insert(pair('I',1)); 16 | hm.insert(pair('V',5)); 17 | hm.insert(pair('X',10)); 18 | hm.insert(pair('L',50)); 19 | hm.insert(pair('C',100)); 20 | hm.insert(pair('D',500)); 21 | hm.insert(pair('M',1000)); 22 | int sum=hm[s[s.size()-1]]; 23 | for(int i=s.size()-1;i>0;--i){ 24 | if(hm[s[i]]>hm[s[i-1]]){ 25 | sum-=hm[s[i-1]]; 26 | }else{ 27 | sum+=hm[s[i-1]]; 28 | } 29 | } 30 | return sum; 31 | } 32 | }; -------------------------------------------------------------------------------- /027-Remove-Element.cpp: -------------------------------------------------------------------------------- 1 | 27. Remove Element 2 | 3 | Given an array and a value, remove all instances of that value in place and return the new length. 4 | 5 | Do not allocate extra space for another array, you must do this in place with constant memory. 6 | 7 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 8 | 9 | Example: 10 | Given input array nums = [3,2,2,3], val = 3 11 | 12 | Your function should return length = 2, with the first two elements of nums being 2. 13 | 14 | 15 | 16 | 17 | 思路:设置index=0;从头开始遍历,当前元素不为val,则将当前元素存在在index位置,index++; 18 | 19 | class Solution { 20 | public: 21 | int removeElement(vector& nums, int val) { 22 | int index=0; 23 | for(int j=0;j& nums) { 20 | int index=0; 21 | for(int i=0;i1->2, return 1->2. 8 | 9 | Given 1->1->2->3->3, return 1->2->3. 10 | 11 | 12 | 思路:遍历一次链表即可,每遍历一个元素比较其是否与它的下一个元素相等。若是,指针指向下下个元素;否则继续遍历下一个元素。 13 | 14 | /** 15 | * Definition for singly-linked list. 16 | * public class ListNode { 17 | * int val; 18 | * ListNode next; 19 | * ListNode(int x) { val = x; } 20 | * } 21 | */ 22 | class Solution { 23 | public ListNode deleteDuplicates(ListNode head) { 24 | if(head==null){ 25 | return null; 26 | } 27 | ListNode p = head; 28 | while(p.next!=null){ 29 | if(p.val == p.next.val){ 30 | p.next = p.next.next; 31 | }else{ 32 | p = p.next; 33 | } 34 | } 35 | return head; 36 | } 37 | } -------------------------------------------------------------------------------- /100-Same-Tree.cpp: -------------------------------------------------------------------------------- 1 | 100. Same Tree 2 | 3 | Given two binary trees, write a function to check if they are equal or not. 4 | 5 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 6 | 7 | 8 | 9 | 10 | 11 | /** 12 | * Definition for a binary tree node. 13 | * struct TreeNode { 14 | * int val; 15 | * TreeNode *left; 16 | * TreeNode *right; 17 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 18 | * }; 19 | */ 20 | class Solution { 21 | public: 22 | bool isSameTree(TreeNode* p, TreeNode* q) { 23 | if(p==nullptr && q==nullptr){ 24 | return true; 25 | } 26 | else if(p==nullptr || q==nullptr){ 27 | return false; 28 | } 29 | 30 | if(p->val!=q->val){ 31 | return false; 32 | }else{ 33 | return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right); 34 | } 35 | 36 | } 37 | }; -------------------------------------------------------------------------------- /104-Maximum-Depth-Of-Binary-Tree.cpp: -------------------------------------------------------------------------------- 1 | 104. Maximum Depth of Binary Tree 2 | 3 | Given a binary tree, find its maximum depth. 4 | 5 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 6 | 7 | Subscribe to see which companies asked this question. 8 | 9 | 10 | 11 | 12 | 13 | /** 14 | * Definition for binary tree 15 | * struct TreeNode { 16 | * int val; 17 | * TreeNode *left; 18 | * TreeNode *right; 19 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 20 | * }; 21 | */ 22 | class Solution { 23 | public: 24 | int maxDepth(TreeNode *root) { 25 | int Ldepth=0,Rdepth=0; 26 | if(root==NULL){ 27 | return 0; 28 | } 29 | if(root->left==NULL && root->right==NULL){ 30 | return 1; 31 | } 32 | Ldepth=maxDepth(root->left); 33 | Rdepth=maxDepth(root->right); 34 | 35 | return 1+(Ldepth>Rdepth?Ldepth:Rdepth); 36 | } 37 | }; -------------------------------------------------------------------------------- /094-Binary-Tree-Inorder-Traversal.java: -------------------------------------------------------------------------------- 1 | 94. Binary Tree Inorder Traversal 2 | 3 | Given a binary tree, return the inorder traversal of its nodes' values. 4 | 5 | For example: 6 | Given binary tree [1,null,2,3], 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | return [1,3,2]. 13 | 14 | 思路: 15 | 二叉树的中序遍历,这里直接用递归的方法求解。 16 | 17 | /** 18 | * Definition for a binary tree node. 19 | * public class TreeNode { 20 | * int val; 21 | * TreeNode left; 22 | * TreeNode right; 23 | * TreeNode(int x) { val = x; } 24 | * } 25 | */ 26 | class Solution { 27 | public List inorderTraversal(TreeNode root) { 28 | List ret = new ArrayList(); 29 | inorder(root,ret); 30 | return ret; 31 | } 32 | 33 | public void inorder(TreeNode root, List ret){ 34 | if(root==null){ 35 | return ; 36 | } 37 | inorder(root.left,ret); 38 | ret.add(root.val); 39 | inorder(root.right,ret); 40 | } 41 | } -------------------------------------------------------------------------------- /242-Valid-Anagram.cpp: -------------------------------------------------------------------------------- 1 | 242. Valid Anagram 2 | 3 | Given two strings s and t, write a function to determine if t is an anagram of s. 4 | 5 | For example, 6 | s = "anagram", t = "nagaram", return true. 7 | s = "rat", t = "car", return false. 8 | 9 | Note: 10 | You may assume the string contains only lowercase alphabets. 11 | 12 | Follow up: 13 | What if the inputs contain unicode characters? How would you adapt your solution to such case? 14 | 15 | 16 | 17 | 18 | class Solution { 19 | public: 20 | bool isAnagram(string s, string t) { 21 | if(s.size()!=t.size()){ 22 | return false; 23 | } 24 | int arr[26]; 25 | for(int i=0;i<26;++i){ 26 | arr[i]=0; 27 | } 28 | for(int i=0;ival)<=(l2->val)){ 26 | newhead=l1; 27 | newhead->next = mergeTwoLists(l1->next,l2); 28 | }else{ 29 | newhead=l2; 30 | newhead->next = mergeTwoLists(l1,l2->next); 31 | } 32 | return newhead; 33 | } 34 | }; -------------------------------------------------------------------------------- /476-Number-Complement.cpp: -------------------------------------------------------------------------------- 1 | 476. Number Complement 2 | 3 | Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. 4 | 5 | Note: 6 | The given integer is guaranteed to fit within the range of a 32-bit signed integer. 7 | You could assume no leading zero bit in the integer’s binary representation. 8 | Example 1: 9 | Input: 5 10 | Output: 2 11 | Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. 12 | Example 2: 13 | Input: 1 14 | Output: 0 15 | Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. 16 | 17 | 18 | 19 | 20 | 21 | class Solution { 22 | public: 23 | int findComplement(int num) { 24 | int sum=0,val=1; 25 | while(num>0){ 26 | if(num%2==0){ 27 | sum+=val; 28 | } 29 | val *= 2; 30 | num/=2; 31 | } 32 | return sum; 33 | } 34 | }; -------------------------------------------------------------------------------- /009-Palindrome-Number.cpp: -------------------------------------------------------------------------------- 1 | 9. Palindrome Number 2 | 3 | Determine whether an integer is a palindrome. Do this without extra space. 4 | 5 | click to show spoilers. 6 | 7 | Some hints: 8 | Could negative integers be palindromes? (ie, -1) 9 | 10 | If you are thinking of converting the integer to string, note the restriction of using extra space. 11 | 12 | You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? 13 | 14 | There is a more generic way of solving this problem. 15 | 16 | 17 | 18 | 思路: 19 | 1. 本方法只需判断x的前(n/2)位是否等于x的后(n/2)位的逆序,是则为回文数,否则不是回文数; 20 | 2. 当x的位数为偶数,则判断x是否等t;当x的位数为奇数,t的位数比x大一位,则判断x是是否等于t/10。 21 | 22 | 23 | class Solution { 24 | public: 25 | bool isPalindrome(int x) { 26 | if(x<0||(x!=0&&x%10==0)){ 27 | return false; 28 | } 29 | int t=0; 30 | while(x>t){ 31 | t = 10*t+x%10; 32 | x /= 10; 33 | } 34 | return (x==t)||(x==t/10); 35 | } 36 | }; -------------------------------------------------------------------------------- /448-Find-All-Numbers-Disappeared-in-an-Array.cpp: -------------------------------------------------------------------------------- 1 | 448. Find All Numbers Disappeared in an Array 2 | 3 | Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 4 | 5 | Find all the elements of [1, n] inclusive that do not appear in this array. 6 | 7 | Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. 8 | 9 | Example: 10 | 11 | Input: 12 | [4,3,2,7,8,2,3,1] 13 | 14 | Output: 15 | [5,6] 16 | 17 | 18 | 19 | 20 | 21 | 22 | class Solution { 23 | public: 24 | vector findDisappearedNumbers(vector& nums) { 25 | vector ret; 26 | 27 | for(int i=0;i& nums) { 23 | if(nums.size()==0){ 24 | return 0; 25 | } 26 | int index=1; 27 | for(int i=1;i(2*k)){ 19 | reverse(s.begin()+start,s.begin()+start+k); 20 | start+=2*k; 21 | } 22 | if(end-start+1>=k){ 23 | reverse(s.begin()+start,s.begin()+start+k); 24 | }else{ 25 | reverse(s.begin()+start,s.end()); 26 | } 27 | return s; 28 | } 29 | }; -------------------------------------------------------------------------------- /121-Best-Time-to-Buy-and-Sell-Stock.cpp: -------------------------------------------------------------------------------- 1 | 121. Best Time to Buy and Sell Stock 2 | 3 | Say you have an array for which the ith element is the price of a given stock on day i. 4 | 5 | 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. 6 | 7 | Example 1: 8 | Input: [7, 1, 5, 3, 6, 4] 9 | Output: 5 10 | 11 | max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 12 | Example 2: 13 | Input: [7, 6, 4, 3, 1] 14 | Output: 0 15 | 16 | In this case, no transaction is done, i.e. max profit = 0. 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | class Solution { 25 | public: 26 | int maxProfit(vector& prices) { 27 | if(prices.size()<2){ 28 | return 0; 29 | } 30 | int min=INT_MAX; 31 | int profit=0; 32 | for(int i=0;i(prices[i]-min)?profit:(prices[i]-min); 35 | } 36 | return profit; 37 | } 38 | }; -------------------------------------------------------------------------------- /551-Student-Attendance-Record-I.cpp: -------------------------------------------------------------------------------- 1 | 551. Student Attendance Record IYou are given a string representing an attendance record for a student. The record only contains the following three characters: 2 | 3 | 'A' : Absent. 4 | 'L' : Late. 5 | 'P' : Present. 6 | A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). 7 | 8 | You need to return whether the student could be rewarded according to his attendance record. 9 | 10 | Example 1: 11 | Input: "PPALLP" 12 | Output: True 13 | Example 2: 14 | Input: "PPALLL" 15 | Output: False 16 | 17 | 18 | 19 | 20 | class Solution { 21 | public: 22 | bool checkRecord(string s) { 23 | int a=0,l=0; 24 | for(int i=0;i2) return false; 28 | }else{ 29 | l=0; 30 | } 31 | if(s[i]=='A'){ 32 | a++; 33 | if(a>1) return false; 34 | } 35 | } 36 | return true; 37 | } 38 | }; -------------------------------------------------------------------------------- /461-Hamming-Distance.cpp: -------------------------------------------------------------------------------- 1 | 461. Hamming Distance 2 | 3 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 4 | 5 | Given two integers x and y, calculate the Hamming distance. 6 | 7 | Note: 8 | 0 ≤ x, y < 231. 9 | 10 | Example: 11 | 12 | Input: x = 1, y = 4 13 | 14 | Output: 2 15 | 16 | Explanation: 17 | 1 (0 0 0 1) 18 | 4 (0 1 0 0) 19 | ↑ ↑ 20 | 21 | The above arrows point to positions where the corresponding bits are different. 22 | 23 | 24 | 25 | 26 | class Solution { 27 | public: 28 | int hammingDistance(int x, int y) { 29 | int cnt=0; 30 | while(x>0||y>0){ 31 | if(x%2!=y%2){ 32 | cnt++; 33 | } 34 | x/=2; 35 | y/=2; 36 | } 37 | while(x>0){ 38 | if(x%2==1){ 39 | cnt++; 40 | } 41 | x/=2; 42 | } 43 | while(y>0){ 44 | if(y%2==1){ 45 | cnt++; 46 | } 47 | y/=2; 48 | } 49 | return cnt; 50 | } 51 | }; -------------------------------------------------------------------------------- /066-Plus-One.java: -------------------------------------------------------------------------------- 1 | 66. Plus One 2 | 3 | Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. 4 | 5 | You may assume the integer do not contain any leading zero, except the number 0 itself. 6 | 7 | The digits are stored such that the most significant digit is at the head of the list. 8 | 9 | 10 | 思路:题目的意思是将数组当成一个整数,然后对这个整数加一,返回结果。比如[9,9,9]返回[1,0,0,0];[9,9,8]返回[9,9,9]。 11 | 12 | 从数组最右边开始遍历: 13 | 14 | 1. 如果当前元素小于 8 ,则将当前元素加 1 后,直接返回数组 digits ; 15 | 2. 如果当前元素等于 9 ,将当前元素置为 0 ,继续判断; 16 | 3. 若遍历结束还没返回结果,说明数组 digits 内的元素全为 9 ,则创建一个新的数组,首位为 1 ,其余位为 0 ,返回新数组。 17 | 18 | 19 | class Solution { 20 | public int[] plusOne(int[] digits) { 21 | int len = digits.length; 22 | if(len==0){ 23 | return digits; 24 | } 25 | for(int i=len-1;i>=0;i--){ 26 | if(digits[i]<9){ 27 | digits[i]++; 28 | return digits; 29 | }else{ 30 | digits[i] = 0; 31 | } 32 | } 33 | int[] ret = new int[len+1]; 34 | ret[0] = 1; 35 | return ret; 36 | } 37 | } -------------------------------------------------------------------------------- /404-Sum-of-Left-Leaves.cpp: -------------------------------------------------------------------------------- 1 | 404. Sum of Left Leaves 2 | 3 | Find the sum of all left leaves in a given binary tree. 4 | 5 | Example: 6 | 7 | 3 8 | / \ 9 | 9 20 10 | / \ 11 | 15 7 12 | 13 | There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 14 | 15 | 16 | 17 | 18 | 19 | 20 | /** 21 | * Definition for a binary tree node. 22 | * struct TreeNode { 23 | * int val; 24 | * TreeNode *left; 25 | * TreeNode *right; 26 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | int sumOfLeftLeaves(TreeNode* root) { 32 | if(root==nullptr){ 33 | return 0; 34 | } 35 | int sum=0; 36 | if(root->left){ 37 | if(root->left->left==nullptr && root->left->right==nullptr){ 38 | sum+=root->left->val; 39 | }else{ 40 | sum+=sumOfLeftLeaves(root->left); 41 | } 42 | } 43 | if(root->right){ 44 | sum+=sumOfLeftLeaves(root->right); 45 | } 46 | return sum; 47 | } 48 | }; -------------------------------------------------------------------------------- /226-Invert-Binary-Tree.cpp: -------------------------------------------------------------------------------- 1 | 226. Invert Binary Tree 2 | 3 | Invert a binary tree. 4 | 5 | 4 6 | / \ 7 | 2 7 8 | / \ / \ 9 | 1 3 6 9 10 | to 11 | 4 12 | / \ 13 | 7 2 14 | / \ / \ 15 | 9 6 3 1 16 | Trivia: 17 | This problem was inspired by this original tweet by Max Howell: 18 | Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off. 19 | 20 | 21 | 22 | 23 | 24 | 25 | /** 26 | * Definition for a binary tree node. 27 | * struct TreeNode { 28 | * int val; 29 | * TreeNode *left; 30 | * TreeNode *right; 31 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 32 | * }; 33 | */ 34 | class Solution { 35 | public: 36 | TreeNode* invertTree(TreeNode* root) { 37 | if(root==NULL){ 38 | return NULL; 39 | } 40 | 41 | TreeNode* nl; 42 | TreeNode* nr; 43 | nl = invertTree(root->right); 44 | nr = invertTree(root->left); 45 | 46 | root->left = nl; 47 | root->right = nr; 48 | 49 | return root; 50 | } 51 | }; -------------------------------------------------------------------------------- /167-Two-Sum-II-Input-array-is-sorted.cpp: -------------------------------------------------------------------------------- 1 | 167. Two Sum II - Input array is sorted 2 | 3 | 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. 4 | 5 | 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. 6 | 7 | You may assume that each input would have exactly one solution and you may not use the same element twice. 8 | 9 | Input: numbers={2, 7, 11, 15}, target=9 10 | Output: index1=1, index2=2 11 | 12 | 13 | 14 | 15 | 16 | 17 | class Solution { 18 | public: 19 | vector twoSum(vector& numbers, int target) { 20 | int low=0,high=numbers.size()-1; 21 | int sum = numbers[low]+numbers[high]; 22 | while(sum!=target){ 23 | if(sumtarget){ 34 | right = mid-1; 35 | }else{ 36 | left = mid+1; 37 | } 38 | } 39 | 40 | return nums[mid]>target?mid:mid+1; 41 | } 42 | } -------------------------------------------------------------------------------- /557-Reverse-Words-in-a-String-III.cpp: -------------------------------------------------------------------------------- 1 | 557. Reverse Words in a String III 2 | 3 | Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. 4 | 5 | Example 1: 6 | Input: "Let's take LeetCode contest" 7 | Output: "s'teL ekat edoCteeL tsetnoc" 8 | Note: In the string, each word is separated by single space and there will not be any extra space in the string. 9 | 10 | 11 | 12 | 13 | 14 | class Solution { 15 | public: 16 | string reverseWords(string s) { 17 | vector stack; 18 | int index = 0; 19 | 20 | for(int i=0;i& height) { 18 | int left = 0; 19 | int right = height.size()-1; 20 | int area = 0; 21 | 22 | while(left false 11 | canConstruct("aa", "ab") -> false 12 | canConstruct("aa", "aab") -> true 13 | 14 | 15 | 16 | 17 | 18 | 19 | class Solution { 20 | public: 21 | bool canConstruct(string ransomNote, string magazine) { 22 | if(magazine.size() alp(26,0); 26 | for(int i=0;i=0&&i2>=0){ 20 | if(nums1[i1]>=nums2[i2]){ 21 | nums1[index] = nums1[i1]; 22 | i1--; 23 | }else{ 24 | nums1[index] = nums2[i2]; 25 | i2--; 26 | } 27 | index--; 28 | } 29 | while(i1>=0){ 30 | nums1[index] = nums1[i1]; 31 | i1--; 32 | index--; 33 | } 34 | while(i2>=0){ 35 | nums1[index] = nums2[i2]; 36 | i2--; 37 | index--; 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /006-ZigZag-Conversion.cpp: -------------------------------------------------------------------------------- 1 | 6. ZigZag Conversion 2 | 3 | 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) 4 | 5 | P A H N 6 | A P L S I I G 7 | Y I R 8 | And then read line by line: "PAHNAPLSIIGYIR" 9 | Write the code that will take a string and make this conversion given a number of rows: 10 | 11 | string convert(string text, int nRows); 12 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 13 | 14 | 15 | 16 | 17 | 18 | class Solution { 19 | public: 20 | string convert(string s, int numRows) { 21 | if(numRows==1){ 22 | return s; 23 | } 24 | 25 | string ret=""; 26 | int dist1 = numRows*2-2; 27 | 28 | for(int i=0;i>& points) { 27 | int ret=0; 28 | for(int i=0;i hm; 30 | for(int j=0;jsecond*(iter->second-1); 37 | } 38 | } 39 | return ret; 40 | } 41 | }; -------------------------------------------------------------------------------- /350-Intersection-of-Two-Arrays-II.cpp: -------------------------------------------------------------------------------- 1 | 350. Intersection of Two Arrays II 2 | 3 | Given two arrays, write a function to compute their intersection. 4 | 5 | Example: 6 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. 7 | 8 | Note: 9 | Each element in the result should appear as many times as it shows in both arrays. 10 | The result can be in any order. 11 | Follow up: 12 | What if the given array is already sorted? How would you optimize your algorithm? 13 | What if nums1's size is small compared to nums2's size? Which algorithm is better? 14 | What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | class Solution { 23 | public: 24 | vector intersect(vector& nums1, vector& nums2) { 25 | vector ret; 26 | if (nums1.size() == 0 || nums2.size() == 0) { 27 | return ret; 28 | } 29 | unordered_map hm; 30 | for(int num1:nums1){ 31 | hm[num1]++; 32 | } 33 | for(int num2:nums2){ 34 | if(hm[num2]>0){ 35 | ret.push_back(num2); 36 | hm[num2]--; 37 | } 38 | } 39 | return ret; 40 | } 41 | }; -------------------------------------------------------------------------------- /409-Longest-Palindrome.cpp: -------------------------------------------------------------------------------- 1 | 409. Longest Palindrome 2 | 3 | Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. 4 | 5 | This is case sensitive, for example "Aa" is not considered a palindrome here. 6 | 7 | Note: 8 | Assume the length of given string will not exceed 1,010. 9 | 10 | Example: 11 | 12 | Input: 13 | "abccccdd" 14 | 15 | Output: 16 | 7 17 | 18 | Explanation: 19 | One longest palindrome that can be built is "dccaccd", whose length is 7. 20 | 21 | 22 | 23 | 24 | 25 | class Solution { 26 | public: 27 | int longestPalindrome(string s) { 28 | int alph[52]; 29 | for(int i=0;i<52;++i){ 30 | alph[i]=0; 31 | } 32 | for(int i=0;i='A'&&s[i]<='Z'){ 34 | ++alph[s[i]-'A'+26]; 35 | }else{ 36 | ++alph[s[i]-'a']; 37 | } 38 | } 39 | int flag=0; 40 | int sum=0; 41 | for(int i=0;i<52;++i){ 42 | if(flag==0){ 43 | if(alph[i]&1==1){ 44 | flag=1; 45 | } 46 | } 47 | sum+=alph[i]/2; 48 | } 49 | sum=2*sum+flag; 50 | return sum; 51 | } 52 | }; 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /038-Count-and-Say.cpp: -------------------------------------------------------------------------------- 1 | 38. Count and Say 2 | 3 | The count-and-say sequence is the sequence of integers with the first five terms as following: 4 | 5 | 1. 1 6 | 2. 11 7 | 3. 21 8 | 4. 1211 9 | 5. 111221 10 | 11 | 1 is read off as "one 1" or 11. 12 | 11 is read off as "two 1s" or 21. 13 | 21 is read off as "one 2, then one 1" or 1211. 14 | Given an integer n, generate the nth term of the count-and-say sequence. 15 | 16 | Note: Each term of the sequence of integers will be represented as a string. 17 | 18 | Example 1: 19 | 20 | Input: 1 21 | Output: "1" 22 | Example 2: 23 | 24 | Input: 4 25 | Output: "1211" 26 | 27 | 28 | 思路:题目有点不好理解,大概的意思用口语读书。如,1读作“1”;2就是读1的数,“一个1”,也就是“11”;就是读2的数,“两个1”,也就是“21”;4就是读3的数,“一个2一个1”,也就是“1211”,以此类推,5读作“一个1一个2两个1”,也就是“111221”。最终,输出第n个的读法。 29 | 30 | 31 | 32 | 33 | class Solution { 34 | public: 35 | string countAndSay(int n) { 36 | string str = "1"; 37 | for(int i=1;i ret; 37 | int getMinimumDifference(TreeNode* root) { 38 | travPush(root); 39 | sort(ret.begin(),ret.end()); 40 | int dis = ret[1]-ret[0]; 41 | for(int i=2;ival); 53 | travPush(root->left); 54 | travPush(root->right); 55 | } 56 | }; -------------------------------------------------------------------------------- /492-Construct-the-Rectangle.cpp: -------------------------------------------------------------------------------- 1 | 492. Construct the Rectangle 2 | 3 | For a web developer, it is very important to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 4 | 5 | 1. The area of the rectangular web page you designed must equal to the given target area. 6 | 7 | 2. The width W should not be larger than the length L, which means L >= W. 8 | 9 | 3. The difference between length L and width W should be as small as possible. 10 | You need to output the length L and the width W of the web page you designed in sequence. 11 | Example: 12 | Input: 4 13 | Output: [2, 2] 14 | Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. 15 | But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2. 16 | Note: 17 | The given area won't exceed 10,000,000 and is a positive integer 18 | The web page's width and length you designed must be positive integers. 19 | 20 | 21 | 22 | 23 | 24 | 25 | class Solution { 26 | public: 27 | vector constructRectangle(int area) { 28 | for(int i=sqrt(area);i>0;i--){ 29 | if(area%i==0){ 30 | return {area/i,i}; 31 | } 32 | } 33 | } 34 | }; -------------------------------------------------------------------------------- /238-Product-of-Array-Except-Self.java: -------------------------------------------------------------------------------- 1 | 238. Product of Array Except Self 2 | 3 | Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 4 | 5 | Solve it without division and in O(n). 6 | 7 | For example, given [1,2,3,4], return [24,12,8,6]. 8 | 9 | Follow up: 10 | Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) 11 | 12 | 13 | 14 | 15 | 思路:注意陷阱,要考虑完全。 16 | 1. nums数组全为0; 17 | 2. nums数组只有一个元素为0; 18 | 3. nums数组有两个以上元素为0; 19 | 4. nums数组全不为0。 20 | 21 | 这里用count来计数,分别处理不同的情况。 22 | 23 | 24 | 25 | class Solution { 26 | public int[] productExceptSelf(int[] nums) { 27 | int p = 1; 28 | int count = 0; 29 | int len = nums.length; 30 | int t[] = new int[len]; 31 | 32 | for(int num:nums){ 33 | if(num!=0){ 34 | p *= num; 35 | }else{ 36 | count++; 37 | } 38 | } 39 | if(count==len){ 40 | return nums; 41 | } 42 | 43 | for(int i=0;i1?0:p; 46 | return t; 47 | } 48 | nums[i] = p/nums[i]; 49 | } 50 | 51 | return nums; 52 | } 53 | } -------------------------------------------------------------------------------- /412-Fizz-Buzz.cpp: -------------------------------------------------------------------------------- 1 | 412. Fizz Buzz 2 | 3 | Write a program that outputs the string representation of numbers from 1 to n. 4 | 5 | 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”. 6 | 7 | Example: 8 | 9 | n = 15, 10 | 11 | Return: 12 | [ 13 | "1", 14 | "2", 15 | "Fizz", 16 | "4", 17 | "Buzz", 18 | "Fizz", 19 | "7", 20 | "8", 21 | "Fizz", 22 | "Buzz", 23 | "11", 24 | "Fizz", 25 | "13", 26 | "14", 27 | "FizzBuzz" 28 | ] 29 | 30 | 31 | 32 | 33 | 34 | 35 | class Solution { 36 | public: 37 | vector fizzBuzz(int n) { 38 | vector res; 39 | for(int i=1;i<=n;i++){ 40 | if(i%3==0 || i%5==0){ 41 | if(i%3==0 && i%5==0){ 42 | res.push_back("FizzBuzz"); 43 | } 44 | else if(i%3==0){ 45 | res.push_back("Fizz"); 46 | }else if(i%5==0){ 47 | res.push_back("Buzz"); 48 | } 49 | 50 | }else{ 51 | char temp[256]; 52 | sprintf(temp,"%d",i); 53 | string str = temp; 54 | res.push_back(str); 55 | } 56 | } 57 | return res; 58 | } 59 | }; 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /414-Third-Maximum-Number.cpp: -------------------------------------------------------------------------------- 1 | 414. Third Maximum Number 2 | 3 | Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). 4 | 5 | Example 1: 6 | Input: [3, 2, 1] 7 | 8 | Output: 1 9 | 10 | Explanation: The third maximum is 1. 11 | Example 2: 12 | Input: [1, 2] 13 | 14 | Output: 2 15 | 16 | Explanation: The third maximum does not exist, so the maximum (2) is returned instead. 17 | Example 3: 18 | Input: [2, 2, 3, 1] 19 | 20 | Output: 1 21 | 22 | Explanation: Note that the third maximum here means the third maximum distinct number. 23 | Both numbers with value 2 are both considered as second maximum. 24 | 25 | 26 | 27 | 28 | 29 | class Solution { 30 | public: 31 | int thirdMax(vector& nums) { 32 | long first=LONG_MIN,second=LONG_MIN,third=LONG_MIN; 33 | for(int i=0;ifirst){ 35 | third = second; 36 | second = first; 37 | first = nums[i]; 38 | } 39 | else if(nums[i]second){ 40 | third = second; 41 | second = nums[i]; 42 | } 43 | else if(nums[i]third){ 44 | third = nums[i]; 45 | } 46 | } 47 | return (third==LONG_MIN||third==second)?first:third; 48 | } 49 | }; -------------------------------------------------------------------------------- /463-Island-Perimeter.cpp: -------------------------------------------------------------------------------- 1 | 463. Island Perimeter 2 | 3 | You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. 4 | 5 | Example: 6 | 7 | [[0,1,0,0], 8 | [1,1,1,0], 9 | [0,1,0,0], 10 | [1,1,0,0]] 11 | 12 | Answer: 16 13 | Explanation: The perimeter is the 16 yellow stripes in the image below: 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | class Solution { 22 | public: 23 | int islandPerimeter(vector>& grid) { 24 | int sum=0; 25 | 26 | for(int i=0;i>& ops) { 45 | int numl=m,numr=n; 46 | for(int i=0;i=0 && nums[l]==target){ 30 | l--; 31 | } 32 | while(r<=nums.length-1 && nums[r]==target){ 33 | r++; 34 | } 35 | ret[0] = l+1; 36 | ret[1] = r-1; 37 | return ret; 38 | }else{ 39 | if(nums[mid]lenb?lena:lenb; 34 | } 35 | } 36 | }; -------------------------------------------------------------------------------- /500-Keyboard-Row.cpp: -------------------------------------------------------------------------------- 1 | 500. Keyboard Row 2 | 3 | Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. 4 | 5 | 6 | American keyboard 7 | 8 | 9 | Example 1: 10 | Input: ["Hello", "Alaska", "Dad", "Peace"] 11 | Output: ["Alaska", "Dad"] 12 | Note: 13 | You may use one character in the keyboard more than once. 14 | You may assume the input string will only contain letters of alphabet. 15 | 16 | 17 | 18 | 19 | 20 | 21 | class Solution { 22 | public: 23 | vector findWords(vector& words) { 24 | unordered_set row1 = {'q','w','e','r','t','y','u','i','o','p'}; 25 | unordered_set row2 = {'a','s','d','f','g','h','j','k','l'}; 26 | unordered_set row3 = {'z','x','c','v','b','n','m'}; 27 | vector res; 28 | 29 | for(string word:words){ 30 | int flag1=0; 31 | int flag2=0; 32 | int flag3=0; 33 | for(char ch:word){ 34 | if(row1.count(ch)){ 35 | flag1 = 1; 36 | } 37 | if(row2.count(ch)){ 38 | flag2 = 1; 39 | } 40 | if(row3.count(ch)){ 41 | flag3 = 1; 42 | } 43 | } 44 | if(flag1+flag2+flag3==1){ 45 | res.push_back(word); 46 | } 47 | } 48 | return res; 49 | } 50 | }; -------------------------------------------------------------------------------- /520-Detect-Capital.cpp: -------------------------------------------------------------------------------- 1 | 520. Detect Capital 2 | 3 | Given a word, you need to judge whether the usage of capitals in it is right or not. 4 | 5 | We define the usage of capitals in a word to be right when one of the following cases holds: 6 | 7 | All letters in this word are capitals, like "USA". 8 | All letters in this word are not capitals, like "leetcode". 9 | Only the first letter in this word is capital if it has more than one letter, like "Google". 10 | Otherwise, we define that this word doesn't use capitals in a right way. 11 | Example 1: 12 | Input: "USA" 13 | Output: True 14 | Example 2: 15 | Input: "FlaG" 16 | Output: False 17 | Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters. 18 | 19 | 20 | 21 | 22 | 23 | class Solution { 24 | public: 25 | bool detectCapitalUse(string word) { 26 | int flag=0; 27 | int cnt=0; 28 | if(word[0]>='a'&&word[0]<='z'){ 29 | flag = 1; 30 | } 31 | 32 | for(int i=0;i='A'&&word[i]<='Z'){ 34 | cnt++; 35 | } 36 | } 37 | 38 | if(flag==1){ 39 | if(cnt!=0){ 40 | return false; 41 | }else{ 42 | return true; 43 | } 44 | }else{ 45 | if(cnt==1 || cnt==word.size()){ 46 | return true; 47 | }else{ 48 | return false; 49 | } 50 | } 51 | } 52 | }; -------------------------------------------------------------------------------- /563-Binary-Tree-Tilt.cpp: -------------------------------------------------------------------------------- 1 | 563. Binary Tree Tilt 2 | 3 | Given a binary tree, return the tilt of the whole tree. 4 | 5 | The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0. 6 | 7 | The tilt of the whole tree is defined as the sum of all nodes' tilt. 8 | 9 | Example: 10 | Input: 11 | 1 12 | / \ 13 | 2 3 14 | Output: 1 15 | Explanation: 16 | Tilt of node 2 : 0 17 | Tilt of node 3 : 0 18 | Tilt of node 1 : |2-3| = 1 19 | Tilt of binary tree : 0 + 0 + 1 = 1 20 | Note: 21 | 22 | The sum of node values in any subtree won't exceed the range of 32-bit integer. 23 | All the tilt values won't exceed the range of 32-bit integer. 24 | 25 | 26 | 27 | 28 | 29 | 30 | /** 31 | * Definition for a binary tree node. 32 | * struct TreeNode { 33 | * int val; 34 | * TreeNode *left; 35 | * TreeNode *right; 36 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 37 | * }; 38 | */ 39 | class Solution { 40 | public: 41 | int tilt = 0; 42 | int findTilt(TreeNode* root) { 43 | sumNode(root); 44 | return tilt; 45 | } 46 | 47 | private: 48 | int sumNode(TreeNode* root){ 49 | if(root==NULL){ 50 | return 0; 51 | } 52 | int left = sumNode(root->left); 53 | int right = sumNode(root->right); 54 | tilt+=abs(left-right); 55 | return left+right+root->val; 56 | } 57 | }; -------------------------------------------------------------------------------- /543-Diameter-of-Binary-Tree.cpp: -------------------------------------------------------------------------------- 1 | 543. Diameter of Binary Tree 2 | 3 | Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 4 | 5 | Example: 6 | Given a binary tree 7 | 1 8 | / \ 9 | 2 3 10 | / \ 11 | 4 5 12 | Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. 13 | 14 | Note: The length of path between two nodes is represented by the number of edges between them. 15 | 16 | 17 | 18 | 19 | 20 | /** 21 | * Definition for a binary tree node. 22 | * struct TreeNode { 23 | * int val; 24 | * TreeNode *left; 25 | * TreeNode *right; 26 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | int dia=0; 32 | int diameterOfBinaryTree(TreeNode* root) { 33 | if(root==nullptr){ 34 | return 0; 35 | } 36 | if(root->left==nullptr && root->right==nullptr){ 37 | return 0; 38 | } 39 | DepthOfBinaryTree(root); 40 | 41 | return dia; 42 | } 43 | private: 44 | int DepthOfBinaryTree(TreeNode* root){ 45 | if(!root){ 46 | return 0; 47 | } 48 | int left=DepthOfBinaryTree(root->left); 49 | int right=DepthOfBinaryTree(root->right); 50 | dia=max(dia, left+right); 51 | return 1+max(left,right); 52 | } 53 | }; -------------------------------------------------------------------------------- /002-Add-Two-Numbers.cpp: -------------------------------------------------------------------------------- 1 | 2. Add Two Numbers 2 | 3 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 4 | 5 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 6 | 7 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 8 | Output: 7 -> 0 -> 8 9 | 10 | 思路: 11 | 注意两个链表长度可能不同; 12 | 注意最后一个节点相加后产生的进位; 13 | 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * struct ListNode { 18 | * int val; 19 | * ListNode *next; 20 | * ListNode(int x) : val(x), next(NULL) {} 21 | * }; 22 | */ 23 | class Solution { 24 | public: 25 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 26 | ListNode* node1=l1; 27 | ListNode* node2=l2; 28 | ListNode* Node = new ListNode(0); 29 | ListNode* p = Node; 30 | 31 | int num=0; 32 | 33 | while(node1!=NULL || node2!=NULL){ 34 | if(node1!=NULL){ 35 | num+=node1->val; 36 | node1 = node1->next; 37 | } 38 | if(node2!=NULL){ 39 | num+=node2->val; 40 | node2 = node2->next; 41 | } 42 | p->next = new ListNode(num%10); 43 | p = p->next; 44 | num/=10; 45 | } 46 | 47 | if(num==1){ 48 | p->next=new ListNode(1); 49 | } 50 | return Node->next; 51 | } 52 | }; -------------------------------------------------------------------------------- /401-Binary-Watch.cpp: -------------------------------------------------------------------------------- 1 | 401. Binary Watch 2 | 3 | A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). 4 | 5 | Each LED represents a zero or one, with the least significant bit on the right. 6 | 7 | 8 | For example, the above binary watch reads "3:25". 9 | 10 | Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. 11 | 12 | Example: 13 | 14 | Input: n = 1 15 | Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] 16 | Note: 17 | The order of output does not matter. 18 | The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". 19 | The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02". 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | class Solution { 29 | public: 30 | vector readBinaryWatch(int num) { 31 | vector ret; 32 | for(int h=0;h<12;++h){ 33 | for(int m=0;m<60;++m){ 34 | bitset<10> bs(h<<6|m); 35 | if(bs.count()==num){ 36 | string str=to_string(h); 37 | str+=":"; 38 | if(m<10){ 39 | str+="0"; 40 | } 41 | str+=to_string(m); 42 | ret.push_back(str); 43 | } 44 | } 45 | } 46 | return ret; 47 | } 48 | }; -------------------------------------------------------------------------------- /123-Best-Time-to-Buy-and-Sell-Stock-III.java: -------------------------------------------------------------------------------- 1 | 123. Best Time to Buy and Sell Stock III 2 | 3 | Say you have an array for which the ith element is the price of a given stock on day i. 4 | 5 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 6 | 7 | Note: 8 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 9 | 10 | 11 | 思路: 12 | 1. 只能进行两次交易,要求两次交易获利之和最大; 13 | 2. 第一次交易:从前往后遍历,计算每天的最大获利 left[] , left[i] 表示第 i 天的最多能获利多少; 14 | 3. 第二次交易:从后往前遍历,计算每天的最大获利 right[] , right[i] 表示第 i 天的最多能获利多少; 15 | 4. 最大获利:计算哪一天的 left[i] + right[i] 最大,即为两次交易的最大获利。 16 | 17 | 18 | 19 | class Solution { 20 | public int maxProfit(int[] prices) { 21 | int len = prices.length; 22 | if(len<=1){ 23 | return 0; 24 | } 25 | int left[] = new int[len]; 26 | int right[] = new int[len]; 27 | 28 | int min = prices[0]; 29 | left[0] = 0; 30 | for(int i=1;i=0;i--){ 38 | max = Math.max(prices[i],max); 39 | right[i] = Math.max(right[i+1],max-prices[i]); 40 | } 41 | 42 | int profit = 0; 43 | for(int i=0;i= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree. 4 | 5 | Example 1: 6 | Input: 7 | 1 8 | / \ 9 | 0 2 10 | 11 | L = 1 12 | R = 2 13 | 14 | Output: 15 | 1 16 | \ 17 | 2 18 | Example 2: 19 | Input: 20 | 3 21 | / \ 22 | 0 4 23 | \ 24 | 2 25 | / 26 | 1 27 | 28 | L = 1 29 | R = 3 30 | 31 | Output: 32 | 3 33 | / 34 | 2 35 | / 36 | 1 37 | 38 | 39 | 40 | 41 | 思路: 42 | 递归实现。 43 | 1. 如果根节点大于最大值,舍去右子树,左子树为新的树,继续对新的树递归; 44 | 2. 如果根节点小于最小值,舍去左子树,右子树为新的树,继续对新的树递归; 45 | 3. 如果根节点在范围内,则对左右子树重复步骤 1 、 2 。 46 | 47 | /** 48 | * Definition for a binary tree node. 49 | * public class TreeNode { 50 | * int val; 51 | * TreeNode left; 52 | * TreeNode right; 53 | * TreeNode(int x) { val = x; } 54 | * } 55 | */ 56 | class Solution { 57 | public TreeNode trimBST(TreeNode root, int L, int R) { 58 | if(root==null){ 59 | return null; 60 | } 61 | 62 | if(root.val>R){ 63 | root = trimBST(root.left,L,R); 64 | }else if(root.val& candies) { 29 | int num = candies.size(); 30 | int cnt=1; 31 | 32 | sort(candies.begin(),candies.end()); 33 | for(int i=0;inum/2){ 39 | return num/2; 40 | }else{ 41 | return cnt; 42 | } 43 | } 44 | }; -------------------------------------------------------------------------------- /328-Odd-Even-Linked-List.java: -------------------------------------------------------------------------------- 1 | 328. Odd Even Linked List 2 | 3 | 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. 4 | 5 | You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. 6 | 7 | Example: 8 | Given 1->2->3->4->5->NULL, 9 | return 1->3->5->2->4->NULL. 10 | 11 | Note: 12 | The relative order inside both the even and odd groups should remain as it was in the input. 13 | The first node is considered odd, the second node even and so on ... 14 | 15 | 16 | 思路: 17 | 本题通过一次遍历便可实现。设置指针 odd 指向奇数链的链尾,设置指针 even 指向偶数链的链尾,以此遍历,每次更新指针 odd 和 even。 18 | 因为最后要将偶数链接在奇数链的后面,所以一开头应设置指针 even_head 指向偶数链的第一个元素。 19 | 最终,返回 head 。 20 | 21 | 注:在整个流程中, head 始终指向奇数链头, even_head 始终指向偶数链头;奇数链尾 odd 和偶数链尾 even 随着遍历不断更新。 22 | 23 | 24 | 25 | /** 26 | * Definition for singly-linked list. 27 | * public class ListNode { 28 | * int val; 29 | * ListNode next; 30 | * ListNode(int x) { val = x; } 31 | * } 32 | */ 33 | class Solution { 34 | public ListNode oddEvenList(ListNode head) { 35 | if(head==null){ 36 | return null; 37 | } 38 | 39 | ListNode odd = head; 40 | ListNode even = head.next; 41 | ListNode even_head = even; 42 | 43 | while(even!=null&&even.next!=null){ 44 | odd.next = even.next; 45 | odd = odd.next; 46 | even.next = odd.next; 47 | even = even.next; 48 | } 49 | odd.next = even_head; 50 | 51 | return head; 52 | } 53 | } -------------------------------------------------------------------------------- /459-Repeated-Substring-Pattern.java: -------------------------------------------------------------------------------- 1 | 459. Repeated Substring Pattern 2 | 3 | Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. 4 | 5 | Example 1: 6 | Input: "abab" 7 | 8 | Output: True 9 | 10 | Explanation: It's the substring "ab" twice. 11 | Example 2: 12 | Input: "aba" 13 | 14 | Output: False 15 | Example 3: 16 | Input: "abcabcabcabc" 17 | 18 | Output: True 19 | 20 | Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) 21 | 22 | 23 | 24 | 思路: 25 | 1. 先判断字符串s能切割成长度为多少的子串,比如s的长度为9,它只可能切割成长度为1、3的子串; 26 | 2. 根据步骤1,依次判断各种切割方式下,切割后的每个子串是否相等。 27 | 28 | 29 | 30 | 31 | class Solution { 32 | public boolean repeatedSubstringPattern(String s) { 33 | int len = s.length(); 34 | 35 | if(len<2){ 36 | return false; 37 | } 38 | 39 | for(int i=1;i<=len/2;i++){ 40 | if(len%i!=0){ 41 | continue; 42 | } 43 | 44 | String str1 = s.substring(0,i); 45 | boolean match = true; 46 | 47 | for(int j=i;j= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. 4 | 5 | Note: 6 | You may assume the greed factor is always positive. 7 | You cannot assign more than one cookie to one child. 8 | 9 | Example 1: 10 | Input: [1,2,3], [1,1] 11 | 12 | Output: 1 13 | 14 | Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. 15 | And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. 16 | You need to output 1. 17 | Example 2: 18 | Input: [1,2], [1,2,3] 19 | 20 | Output: 2 21 | 22 | Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. 23 | You have 3 cookies and their sizes are big enough to gratify all of the children, 24 | You need to output 2. 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | class Solution { 33 | public: 34 | int findContentChildren(vector& g, vector& s) { 35 | sort(g.begin(),g.end()); 36 | sort(s.begin(),s.end()); 37 | int index = 0; 38 | int cnt = 0; 39 | 40 | for(int i=0;i NULL 27 | / \ 28 | 2 -> 3 -> NULL 29 | / \ / \ 30 | 4->5->6->7 -> NULL 31 | 32 | 思路: 33 | 本题自然要想到二叉树的层序遍历。 34 | 注意右孩子的下一节点的情况,它有可能是 null ,也有可能是其父节点的下一节点的左孩子。 35 | 36 | /** 37 | * Definition for binary tree with next pointer. 38 | * public class TreeLinkNode { 39 | * int val; 40 | * TreeLinkNode left, right, next; 41 | * TreeLinkNode(int x) { val = x; } 42 | * } 43 | */ 44 | public class Solution { 45 | public void connect(TreeLinkNode root) { 46 | if(root==null){ 47 | return; 48 | } 49 | if(root.left!=null){ 50 | root.left.next = root.right; 51 | } 52 | if(root.right!=null){ 53 | root.right.next = root.next!=null?root.next.left:null; 54 | } 55 | 56 | connect(root.left); 57 | connect(root.right); 58 | } 59 | } -------------------------------------------------------------------------------- /617-Merge-Two-Binary-Trees.cpp: -------------------------------------------------------------------------------- 1 | 617. Merge Two Binary Trees 2 | 3 | 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. 4 | 5 | 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. 6 | 7 | Example 1: 8 | Input: 9 | Tree 1 Tree 2 10 | 1 2 11 | / \ / \ 12 | 3 2 1 3 13 | / \ \ 14 | 5 4 7 15 | Output: 16 | Merged tree: 17 | 3 18 | / \ 19 | 4 5 20 | / \ \ 21 | 5 4 7 22 | Note: The merging process must start from the root nodes of both trees. 23 | 24 | 25 | 26 | 27 | /** 28 | * Definition for a binary tree node. 29 | * struct TreeNode { 30 | * int val; 31 | * TreeNode *left; 32 | * TreeNode *right; 33 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 34 | * }; 35 | */ 36 | class Solution { 37 | public: 38 | TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { 39 | if(t1==nullptr){ 40 | return t2; 41 | } 42 | if(t2==nullptr){ 43 | return t1; 44 | } 45 | 46 | t1->val+=t2->val; 47 | t1->left=mergeTrees(t1->left,t2->left); 48 | t1->right=mergeTrees(t1->right,t2->right); 49 | 50 | return t1; 51 | } 52 | }; -------------------------------------------------------------------------------- /415-Add-Strings.cpp: -------------------------------------------------------------------------------- 1 | 415. Add Strings 2 | 3 | Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. 4 | 5 | Note: 6 | 7 | The length of both num1 and num2 is < 5100. 8 | Both num1 and num2 contains only digits 0-9. 9 | Both num1 and num2 does not contain any leading zero. 10 | You must not use any built-in BigInteger library or convert the inputs to integer directly. 11 | 12 | 13 | 14 | 15 | 16 | class Solution { 17 | public: 18 | string addStrings(string num1, string num2) { 19 | string str; 20 | int index1=num1.size()-1; 21 | int index2=num2.size()-1; 22 | int flag=0; 23 | int num; 24 | while(index1>=0&&index2>=0){ 25 | num=(num1[index1--]-'0')+(num2[index2--]-'0')+flag; 26 | if(num>9){ 27 | flag=1; 28 | str.append(to_string(num%10)); 29 | }else{ 30 | flag=0; 31 | str.append(to_string(num)); 32 | } 33 | } 34 | while(index1>=0){ 35 | num=num1[index1--]-'0'+flag; 36 | if(num>9){ 37 | flag=1; 38 | str.append(to_string(num%10)); 39 | }else{ 40 | flag=0; 41 | str.append(to_string(num)); 42 | } 43 | } 44 | while(index2>=0){ 45 | num=num2[index2--]-'0'+flag; 46 | if(num>9){ 47 | flag=1; 48 | str.append(to_string(num%10)); 49 | }else{ 50 | flag=0; 51 | str.append(to_string(num)); 52 | } 53 | } 54 | if(flag==1){ 55 | str.append(to_string(1)); 56 | } 57 | reverse(str.begin(),str.end()); 58 | return str; 59 | } 60 | }; -------------------------------------------------------------------------------- /075-Sort-Colors.java: -------------------------------------------------------------------------------- 1 | 75. Sort Colors 2 | 3 | Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. 4 | 5 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 6 | 7 | Note: 8 | You are not suppose to use the library's sort function for this problem. 9 | 10 | 11 | 思路: 12 | 本题实质上为三元数组排序。 13 | 1. 解法一:借助辅助数组,轻松解决。虽然时间复杂度为 O(n) ,但空间复杂度也为 O(n); 14 | 2. 解法二:不借助辅助数组,直接在原数组进行元素交换。时间复杂度 O(n) ,空间复杂度 O(1)。 15 | 16 | 17 | class Solution { 18 | public void sortColors(int[] nums) { 19 | int len = nums.length; 20 | int[] ret = new int[len]; 21 | int l = 0; 22 | int r = len-1; 23 | 24 | for(int i=0;iright 或 top>buttom 。 22 | 23 | 24 | class Solution { 25 | public List spiralOrder(int[][] matrix) { 26 | 27 | List ret = new LinkedList(); 28 | if(matrix.length==0){ 29 | return ret; 30 | } 31 | int left = 0; 32 | int right = matrix[0].length-1; 33 | int top = 0; 34 | int buttom = matrix.length-1; 35 | int direction = 1; 36 | 37 | while(left<=right&&top<=buttom){ 38 | if(direction==1){ 39 | for(int i=left;i<=right;i++){ 40 | ret.add(matrix[top][i]); 41 | } 42 | top++; 43 | direction = 2; 44 | }else if(direction==2){ 45 | for(int i=top;i<=buttom;i++){ 46 | ret.add(matrix[i][right]); 47 | } 48 | right--; 49 | direction = 3; 50 | }else if(direction==3){ 51 | for(int i=right;i>=left;i--){ 52 | ret.add(matrix[buttom][i]); 53 | } 54 | buttom--; 55 | direction = 4; 56 | }else if(direction==4){ 57 | for(int i=buttom;i>=top;i--){ 58 | ret.add(matrix[i][left]); 59 | } 60 | left++; 61 | direction = 1; 62 | } 63 | } 64 | 65 | return ret; 66 | } 67 | } -------------------------------------------------------------------------------- /566-Reshape-the-Matrix.cpp: -------------------------------------------------------------------------------- 1 | 566. Reshape the Matrix 2 | 3 | In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data. 4 | 5 | You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively. 6 | 7 | The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were. 8 | 9 | If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. 10 | 11 | Example 1: 12 | Input: 13 | nums = 14 | [[1,2], 15 | [3,4]] 16 | r = 1, c = 4 17 | Output: 18 | [[1,2,3,4]] 19 | Explanation: 20 | The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list. 21 | Example 2: 22 | Input: 23 | nums = 24 | [[1,2], 25 | [3,4]] 26 | r = 2, c = 4 27 | Output: 28 | [[1,2], 29 | [3,4]] 30 | Explanation: 31 | There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix. 32 | 33 | 34 | 35 | 36 | class Solution { 37 | public: 38 | vector> matrixReshape(vector>& nums, int r, int c) { 39 | int numsr = nums.size(); 40 | int numsc = nums[0].size(); 41 | if(numsr*numsc!=r*c){ 42 | return nums; 43 | }else{ 44 | vector> res(r, vector(c,0)); 45 | vector num; 46 | for(int i=0;i m = new HashMap<>(); 45 | int count = 0; 46 | 47 | for(int num:nums){ 48 | m.put(num,m.getOrDefault(num,0)+1); 49 | } 50 | 51 | for(Map.Entry entry:m.entrySet()){ 52 | if(0==k){ 53 | if(entry.getValue()>1){ 54 | count++; 55 | } 56 | }else{ 57 | if(m.containsKey(entry.getKey()+k)){ 58 | count++; 59 | } 60 | } 61 | } 62 | 63 | return count; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /059-Spiral-Matrix-II.java: -------------------------------------------------------------------------------- 1 | 59. Spiral Matrix II 2 | 3 | Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 4 | 5 | For example, 6 | Given n = 3, 7 | 8 | You should return the following matrix: 9 | ``` 10 | [ 11 | [ 1, 2, 3 ], 12 | [ 8, 9, 4 ], 13 | [ 7, 6, 5 ] 14 | ] 15 | ``` 16 | 17 | 思路: 18 | 题意要求根据 n ,创建一个 n*n 的回旋矩阵。 19 | 1. 设置 direction ,表示构造方向(向右,向下,向左,向上); 20 | 2. 设置 left、right、top、buttom ,分别指示矩阵左边界、右边界、上边界、下边界; 21 | 3. 设置 count 指示当前的数值; 22 | 4. 按右-下-左-上的顺序不断循环构造,直至 left>right 或 top>buttom 。 23 | 24 | 25 | 26 | class Solution { 27 | public int[][] generateMatrix(int n) { 28 | int[][] ret = new int[n][n]; 29 | if(n==0){ 30 | return ret; 31 | } 32 | int count = 1; 33 | int direction = 1; 34 | int left = 0; 35 | int right = n-1; 36 | int top = 0; 37 | int buttom = n-1; 38 | 39 | while(left<=right&&top<=buttom){ 40 | if(direction==1){ 41 | for(int i=left;i<=right;i++){ 42 | ret[top][i] = count; 43 | count++; 44 | } 45 | top++; 46 | direction = 2; 47 | }else if(direction==2){ 48 | for(int i=top;i<=buttom;i++){ 49 | ret[i][right] = count; 50 | count++; 51 | } 52 | right--; 53 | direction = 3; 54 | }else if(direction==3){ 55 | for(int i=right;i>=left;i--){ 56 | ret[buttom][i] = count; 57 | count++; 58 | } 59 | buttom--; 60 | direction = 4; 61 | }else if(direction==4){ 62 | for(int i=buttom;i>=top;i--){ 63 | ret[i][left] = count; 64 | count++; 65 | 66 | } 67 | left++; 68 | direction = 1; 69 | } 70 | } 71 | 72 | return ret; 73 | } 74 | } -------------------------------------------------------------------------------- /599-Minimum-Index-Sum-of-Two-Lists.cpp: -------------------------------------------------------------------------------- 1 | 599. Minimum Index Sum of Two Lists 2 | 3 | Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. 4 | 5 | You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer. 6 | 7 | Example 1: 8 | Input: 9 | ["Shogun", "Tapioca Express", "Burger King", "KFC"] 10 | ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] 11 | Output: ["Shogun"] 12 | Explanation: The only restaurant they both like is "Shogun". 13 | Example 2: 14 | Input: 15 | ["Shogun", "Tapioca Express", "Burger King", "KFC"] 16 | ["KFC", "Shogun", "Burger King"] 17 | Output: ["Shogun"] 18 | Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1). 19 | Note: 20 | The length of both lists will be in the range of [1, 1000]. 21 | The length of strings in both lists will be in the range of [1, 30]. 22 | The index is starting from 0 to the list length minus 1. 23 | No duplicates in both lists. 24 | 25 | 26 | 27 | 28 | 29 | class Solution { 30 | public: 31 | vector findRestaurant(vector& list1, vector& list2) { 32 | unordered_map m; 33 | unordered_map::iterator iter; 34 | vector ret; 35 | int cnt; 36 | int min=INT_MAX; 37 | 38 | for(int i=0;i(list1[i],i)); 40 | } 41 | for(int j=0;jsecond + j; 45 | if(min>cnt){ 46 | min = cnt; 47 | if(!ret.empty()){ 48 | ret.clear(); 49 | } 50 | ret.push_back(iter->first); 51 | }else if(min==cnt){ 52 | ret.push_back(iter->first); 53 | } 54 | } 55 | } 56 | return ret; 57 | } 58 | }; -------------------------------------------------------------------------------- /523-Continuous-Subarray-Sum.java: -------------------------------------------------------------------------------- 1 | 523. Continuous Subarray Sum 2 | 3 | Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer. 4 | 5 | Example 1: 6 | Input: [23, 2, 4, 6, 7], k=6 7 | Output: True 8 | 9 | Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6. 10 | 11 | Example 2: 12 | Input: [23, 2, 6, 4, 7], k=6 13 | Output: True 14 | 15 | Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42. 16 | 17 | Note: 18 | The length of the array won't exceed 10,000. 19 | You may assume the sum of all the numbers is in the range of a signed 32-bit integer. 20 | 21 | 22 | 23 | 24 | 思路:暴力解之。注意k为0时应单独考虑,判断相邻的元素是否为0,若是返回true,否则返回false。 25 | 26 | 注:此题有O(n)的解法,不过该方法不通用。 27 | 28 | 29 | 30 | 31 | 32 | 33 | 解法1:暴力 34 | 35 | class Solution { 36 | public boolean checkSubarraySum(int[] nums, int k) { 37 | if(k==0){ 38 | return checkzero(nums); 39 | } 40 | 41 | int len = nums.length; 42 | for(int i=0;i0){ 47 | return true; 48 | } 49 | } 50 | } 51 | return false; 52 | } 53 | 54 | private boolean checkzero(int[] nums){ 55 | for(int i=0;i& nums, int k) { 69 | int n = nums.size(), sum = 0, pre = 0; 70 | unordered_set modk; 71 | for (int i = 0; i < n; ++i) { 72 | sum += nums[i]; 73 | int mod = k == 0 ? sum : sum % k; 74 | if (modk.count(mod)) return true; 75 | modk.insert(pre); 76 | pre = mod; 77 | } 78 | return false; 79 | } 80 | }; -------------------------------------------------------------------------------- /537-Complex-Number-Multiplication.cpp: -------------------------------------------------------------------------------- 1 | 537. Complex Number Multiplication 2 | 3 | Given two strings representing two complex numbers. 4 | 5 | You need to return a string representing their multiplication. Note i2 = -1 according to the definition. 6 | 7 | Example 1: 8 | Input: "1+1i", "1+1i" 9 | Output: "0+2i" 10 | Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. 11 | Example 2: 12 | Input: "1+-1i", "1+-1i" 13 | Output: "0+-2i" 14 | Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. 15 | Note: 16 | 17 | The input strings will not have extra blank. 18 | The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form. 19 | 20 | 21 | 22 | 23 | class Solution { 24 | public: 25 | string complexNumberMultiply(string a, string b) { 26 | int a1=0; 27 | int a2=0; 28 | int b1=0; 29 | int b2=0; 30 | int indexa=0; 31 | int indexb=0; 32 | bool minusa1=false; 33 | bool minusa2=false; 34 | bool minusb1=false; 35 | bool minusb2=false; 36 | string ret=""; 37 | 38 | if(a[0]=='-'){ 39 | minusa1=true; 40 | indexa++; 41 | } 42 | if(b[0]=='-'){ 43 | minusb1=true; 44 | indexb++; 45 | } 46 | 47 | while(a[indexa]!='+'){ 48 | a1 = a1*10+(a[indexa]-'0'); 49 | indexa++; 50 | } 51 | while(b[indexb]!='+'){ 52 | b1 = b1*10+(b[indexb]-'0'); 53 | indexb++; 54 | } 55 | a1=minusa1==true?(0-a1):a1; 56 | b1=minusb1==true?(0-b1):b1; 57 | 58 | indexa++; 59 | indexb++; 60 | 61 | if(a[indexa]=='-'){ 62 | minusa2=true; 63 | indexa++; 64 | } 65 | if(b[indexb]=='-'){ 66 | minusb2=true; 67 | indexb++; 68 | } 69 | while(a[indexa]!='i'){ 70 | a2 = a2*10+(a[indexa]-'0'); 71 | indexa++; 72 | } 73 | while(b[indexb]!='i'){ 74 | b2 = b2*10+(b[indexb]-'0'); 75 | indexb++; 76 | } 77 | a2=minusa2==true?(0-a2):a2; 78 | b2=minusb2==true?(0-b2):b2; 79 | cout<=0 && indexB>=0){ 41 | if(a.charAt(indexA)=='1'&&b.charAt(indexB)=='1'){ 42 | ch[indexC] = flag==1?'1':'0'; 43 | flag = 1; 44 | }else if(a.charAt(indexA)=='0'&&b.charAt(indexB)=='0'){ 45 | ch[indexC] = flag==1?'1':'0'; 46 | flag = 0; 47 | }else{ 48 | ch[indexC] = flag==1?'0':'1'; 49 | flag = flag==1?1:0; 50 | } 51 | indexA--; 52 | indexB--; 53 | indexC--; 54 | } 55 | 56 | while(indexA>=0){ 57 | if(a.charAt(indexA)=='1'){ 58 | if(flag==1){ 59 | ch[indexC] = '0'; 60 | flag = 1; 61 | }else{ 62 | ch[indexC] = '1'; 63 | flag = 0; 64 | } 65 | }else{ 66 | ch[indexC] = flag==1?'1':'0'; 67 | flag = 0; 68 | } 69 | indexA--; 70 | indexC--; 71 | } 72 | 73 | while(indexB>=0){ 74 | if(b.charAt(indexB)=='1'){ 75 | if(flag==1){ 76 | ch[indexC] = '0'; 77 | flag = 1; 78 | }else{ 79 | ch[indexC] = '1'; 80 | flag = 0; 81 | } 82 | }else{ 83 | ch[indexC] = flag==1?'1':'0'; 84 | flag = 0; 85 | } 86 | indexB--; 87 | indexC--; 88 | } 89 | if(flag==1){ 90 | ch[0] = '1'; 91 | } 92 | 93 | return new String(ch).trim(); 94 | } 95 | } 96 | 97 | 98 | -------------------------------------------------------------------------------- /008-String-to-Integer(atoi).cpp: -------------------------------------------------------------------------------- 1 | 8. String to Integer (atoi) 2 | 3 | Implement atoi to convert a string to an integer. 4 | 5 | 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. 6 | 7 | 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. 8 | 9 | Update (2015-02-10): 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. 11 | 12 | spoilers alert... click to show requirements for atoi. 13 | 14 | Requirements for atoi: 15 | 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. 16 | 17 | 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. 18 | 19 | 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. 20 | 21 | 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. 22 | 23 | 24 | 25 | 26 | 27 | 28 | class Solution { 29 | public: 30 | bool invaildinput=false; 31 | int myAtoi(string str) { 32 | if(str.length()<1){ 33 | invaildinput=true; 34 | return 0; 35 | } 36 | 37 | bool minus=false; 38 | int index=0; 39 | 40 | while(str[index]==' ') 41 | index++; 42 | 43 | if(str[index]=='-'){ 44 | minus=true; 45 | index++; 46 | } 47 | else if(str[index]=='+') 48 | index++; 49 | 50 | long long result=0; 51 | while(str[index]!='\0'){ 52 | if(str[index]>='0'&&str[index]<='9'){ 53 | result = result*10+(str[index]-'0'); 54 | if(!minus&&result>INT_MAX){ 55 | invaildinput=true; 56 | return INT_MAX; 57 | } 58 | else if(minus&&(0-result)INT_MAX||tINT_MAX||t>>>>>> 900eda1353bac26c39cf9c872352fef166197abb 100 | }; -------------------------------------------------------------------------------- /682-Baseball-Game.java: -------------------------------------------------------------------------------- 1 | 682. Baseball Game 2 | 3 | You're now a baseball game point recorder. 4 | 5 | Given a list of strings, each string can be one of the 4 following types: 6 | 7 | Integer (one round's score): Directly represents the number of points you get in this round. 8 | "+" (one round's score): Represents that the points you get in this round are the sum of the last two valid round's points. 9 | "D" (one round's score): Represents that the points you get in this round are the doubled data of the last valid round's points. 10 | "C" (an operation, which isn't a round's score): Represents the last valid round's points you get were invalid and should be removed. 11 | Each round's operation is permanent and could have an impact on the round before and the round after. 12 | 13 | You need to return the sum of the points you could get in all the rounds. 14 | 15 | Example 1: 16 | Input: ["5","2","C","D","+"] 17 | Output: 30 18 | Explanation: 19 | Round 1: You could get 5 points. The sum is: 5. 20 | Round 2: You could get 2 points. The sum is: 7. 21 | Operation 1: The round 2's data was invalid. The sum is: 5. 22 | Round 3: You could get 10 points (the round 2's data has been removed). The sum is: 15. 23 | Round 4: You could get 5 + 10 = 15 points. The sum is: 30. 24 | Example 2: 25 | Input: ["5","-2","4","C","D","9","+","+"] 26 | Output: 27 27 | Explanation: 28 | Round 1: You could get 5 points. The sum is: 5. 29 | Round 2: You could get -2 points. The sum is: 3. 30 | Round 3: You could get 4 points. The sum is: 7. 31 | Operation 1: The round 3's data is invalid. The sum is: 3. 32 | Round 4: You could get -4 points (the round 3's data has been removed). The sum is: -1. 33 | Round 5: You could get 9 points. The sum is: 8. 34 | Round 6: You could get -4 + 9 = 5 points. The sum is 13. 35 | Round 7: You could get 9 + 5 = 14 points. The sum is 27. 36 | Note: 37 | The size of the input list will be between 1 and 1000. 38 | Every integer represented in the list will be between -30000 and 30000. 39 | 40 | 41 | 42 | 43 | 思路: 44 | 本题应想到用 LinkedList 来实现,链表最后一个元素为前一轮的得分,倒数第二个元素为前前一轮的得分,每一轮记得更新链表。 45 | 1. “C”: score 减去链表最后的元素,并删除链表最后的元素; 46 | 2. “D”: score 加上链表最后元素的2倍,并将链表最后元素的2倍添加到链表最后; 47 | 3. “+”: score 加上链表倒数第一、第二个元素,并将倒数第一第二元素的和添加到链表最后; 48 | 4. 数值:score 加上该数值,并将该数值添加到链表最后。 49 | 50 | 51 | 52 | 53 | class Solution { 54 | public int calPoints(String[] ops) { 55 | int score = 0; 56 | LinkedList list = new LinkedList<>(); 57 | 58 | for(int i=0;i