diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..df0b3ab78 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.DS_Store +*/.DS_Store diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 000000000..35eb1ddfb --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/018429.c b/018429.c new file mode 100644 index 000000000..35d9bb74b --- /dev/null +++ b/018429.c @@ -0,0 +1,18 @@ +int firstUniqChar(char* s) { + int ascii[256]={0}; + int i=0,len; + while(s[i]!='\0') + { + i++; + } + len=i; + for(i=0;i> threeSum(int[] nums) { + final int length = nums.length; + List> result = new ArrayList<>(); + HashMap hashMap = new HashMap(); + + if (length < 3) return result; + + Arrays.sort(nums); + + for (int i = 0; i < length - 2; i++) { + hashMap.clear(); + + if (i == 0 || nums[i] > nums[i - 1]) { + for (int j = i + 1; j < length; j++) { + + if (hashMap.containsKey(nums[j])) { + ArrayList elem = new ArrayList(3); + + elem.add(hashMap.get(nums[j])[0]); + elem.add(hashMap.get(nums[j])[1]); + elem.add(nums[j]); + + result.add(elem); + + while (j < (length - 1) && nums[j] == nums[j + 1]) j++; + } else { + int[] temp = new int[2]; + temp[0] = nums[i]; + temp[1] = nums[j]; + hashMap.put(0 - (nums[i] + nums[j]), temp); + } + } + } + } + return result; + } diff --git a/2018.11.19-leetcode15/Istoryforever.md b/2018.11.19-leetcode15/Istoryforever.md new file mode 100644 index 000000000..a60b386e0 --- /dev/null +++ b/2018.11.19-leetcode15/Istoryforever.md @@ -0,0 +1,46 @@ +leetcode of 15 +``` +class Solution { +public: + vector> threeSum(vector& nums) { + + vector> res; + if(nums.size()==0) return res; + sort(nums.begin(),nums.end()); + int i=0; + int p=0; + int q=0; + while(i0 &&nums[i-1]==nums[i]){ + i++; + continue; + } + if(nums[i]>0) break; + int diff=0-nums[i]; + p=i+1; + q=nums.size()-1; + while(pdiff && ptemp; + temp.push_back(nums[i]); + temp.push_back(nums[p]); + temp.push_back(nums[q]); + res.push_back(temp); + p++; + q--; + while(p> threeSum(vector& nums) { + vector> ans; + int n = nums.size(); + sort(nums.begin(), nums.end()); //排序,从小到大 + for(int i = 0 ; i < n - 2; i ++){ + int j = i + 1; + int k = n - 1; + while(j < k){ + if(nums[i] + nums[j] + nums[k] > 0){ + k --; + } + else if(nums[i] + nums[j] + nums[k] < 0){ + j ++; + } + else{ + ans.push_back({nums[i], nums[j], nums[k]}); + while(nums[j+1] == nums[j]) j++; + j ++; + } + } + while(nums[i+1] == nums[i]) i++; + } + + return ans; + } +}; + +``` diff --git "a/2018.11.19-leetcode15/\346\243\225\346\246\210\346\240\221.md" "b/2018.11.19-leetcode15/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..04d48cf9c --- /dev/null +++ "b/2018.11.19-leetcode15/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,30 @@ +``` +class Solution { + public List> threeSum(int[] nums) { + List> res = new ArrayList<>(); + Arrays.sort(nums); + for(int i=0;i0&&nums[i]!=nums[i-1])){ + while(lowhayStackLength) return -1; if (needleLength == 0) return 0; + for (int i = 0; i haystack.length()) { + return -1; + } + int hStart,nStart; + for (int i = 0; i < haystack.length(); i++) { + hStart=i; + nStart=0; + while (nStart < needle.length() && hStart < haystack.length()) { + if (haystack.charAt(hStart) == needle.charAt(nStart)) { + hStart++; + nStart++; + } else { + break; + } + if (nStart == needle.length()) { + return i; + } + + } + } + return -1; + } diff --git a/2018.11.24-leetcode28/syuan.md b/2018.11.24-leetcode28/syuan.md new file mode 100644 index 000000000..9caed293c --- /dev/null +++ b/2018.11.24-leetcode28/syuan.md @@ -0,0 +1,30 @@ +``` +class Solution { + public int strStr(String haystack, String needle) { + if(needle.length() == 0) + return 0; + char [] charArrayhaystack = haystack.toCharArray(); + char [] charArrayneedle = needle.toCharArray(); + for(int i =0;ilengthHay) { + return -1; + }else{ + while(ilen(haystack): + return(-1) + match=0 + for a in range(len(haystack)-lenNeedle+1): + m = a + match = 0 + for i in range(lenNeedle): + if haystack[m]==needle[i]: + match+=1 + m+=1 + if match == lenNeedle: + break + if match == lenNeedle: + break + if match == lenNeedle: + return(a) + else: + return(-1) + diff --git a/2018.11.25-leetcode80/Istoryforever.md b/2018.11.25-leetcode80/Istoryforever.md new file mode 100644 index 000000000..def5670f2 --- /dev/null +++ b/2018.11.25-leetcode80/Istoryforever.md @@ -0,0 +1,27 @@ +leetcode number 80 +``` +class Solution { +public: + void swap(int &a,int &b){ + int c = a; + a = b; + b = a; + + } + int removeDuplicates(vector& nums) { + int j = -1; + int count = 0; + for(int i = 0;i < nums.size();i++){ + if(i != 0 && nums[i] == nums[i-1]) { + if(count >= 1) continue; + ++count; + } + else + count = 0; + nums[++j]=nums[i]; + } + return j+1; + + } +}; +``` diff --git a/2018.11.25-leetcode80/Tony the Cyclist.md b/2018.11.25-leetcode80/Tony the Cyclist.md new file mode 100644 index 000000000..69a4759ac --- /dev/null +++ b/2018.11.25-leetcode80/Tony the Cyclist.md @@ -0,0 +1,16 @@ +``` + +class Solution { + public int removeDuplicates(int[] nums) { + if (nums.length < 3){ + return nums.length; + } + int pos = 2; + for(int i = 2; i < nums.length; i++){ + if(nums[i]!=nums[pos-2]) + nums[pos++]=nums[i]; + } + return pos; + } +} +``` diff --git a/2018.11.25-leetcode80/syuan.md b/2018.11.25-leetcode80/syuan.md new file mode 100644 index 000000000..69087f2b6 --- /dev/null +++ b/2018.11.25-leetcode80/syuan.md @@ -0,0 +1,83 @@ +##### 题目 + +``` +给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。 + +不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 + +示例 1: + +给定 nums = [1,1,1,2,2,3], + +函数应返回新长度 length = 5, 并且原数组的前五个元素被修改为 1, 1, 2, 2, 3 。 + +你不需要考虑数组中超出新长度后面的元素。 + +示例 2: + +给定 nums = [0,0,1,1,1,1,2,3,3], + +函数应返回新长度 length = 7, 并且原数组的前五个元素被修改为 0, 0, 1, 1, 2, 3, 3 。 + +你不需要考虑数组中超出新长度后面的元素。 + +说明: + +为什么返回数值是整数,但输出的答案是数组呢? + +请注意,输入数组是以“引用”方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。 + +你可以想象内部操作如下: + +// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝 +int len = removeDuplicates(nums); + +// 在函数里修改输入数组对于调用者是可见的。 +// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。 +for (int i = 0; i < len; i++) { + print(nums[i]); +} +``` +##### 代码 + +``` +class Solution { + public int removeDuplicates(int[] nums) { + int count=0; + if (nums.length==1) { + return 1; + } + if (nums.length==0) { + return 0; + } + if (nums.length==2) { + return 2; + } + int i=0; + int j=i; + int tempCount=0; + while(i=2) { + count+=2; + nums[i+1]=nums[i]; + i=i+2; + }else{ + count++; + i++; + } + if (j>=nums.length) { + break; + } + nums[i]=nums[j]; + tempCount=0; + } + } + return count; + } +} +``` diff --git "a/2018.11.25-leetcode80/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.11.25-leetcode80/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..3428058c9 --- /dev/null +++ "b/2018.11.25-leetcode80/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,45 @@ +``` +class Solution { + public int removeDuplicates(int[] nums) { + int count=0; + if(nums.length==0){ + return 0; + } + if(nums.length==0){ + return 1; + } + int i=0; + int j=i;//用来遍历数组 + int tempCount=0; + while(i=2){//统计每个位置数字出现的次数。 + count+=2; + nums[i+1]=nums[i];//保存i的值,前后两个是相同的值,eg 1,1,2,。。 + i=i+2;//i来到下一个的下一个位置。 + }else{//相同的只有两个 + count++; + i++; + } + if(j>=nums.length){ + break; + } + nums[i]=nums[j];// + tempCount=0;//重新统计 + } + + + + } + + + + + + return count; + } +} +``` diff --git a/2018.11.26-leetcode11/FFFro.md b/2018.11.26-leetcode11/FFFro.md new file mode 100644 index 000000000..9d5886e51 --- /dev/null +++ b/2018.11.26-leetcode11/FFFro.md @@ -0,0 +1,25 @@ +class Solution { + public int maxArea(int[] height) { + int start = 0; + int end = height.length-1; + int tempHeight = 0; + int temp = 0; + int result = 0; + while (start < end){ + int ju = end-start; + if (height[start] > height[end]){ + tempHeight = height[end]; + temp = ju*tempHeight; + end--; + }else{ + tempHeight = height[start]; + temp = ju*tempHeight; + start++; + } + if (result < temp){ + result = temp; + } + } + return result; + } +} diff --git a/2018.11.26-leetcode11/Istoryforever.md b/2018.11.26-leetcode11/Istoryforever.md index 184923184..ef7c06b15 100644 --- a/2018.11.26-leetcode11/Istoryforever.md +++ b/2018.11.26-leetcode11/Istoryforever.md @@ -1,3 +1,4 @@ +leetcode11 ``` const int x=[]{ std::ios::sync_with_stdio(false); diff --git a/2018.11.26-leetcode11/Ostrichcrab.md b/2018.11.26-leetcode11/Ostrichcrab.md new file mode 100644 index 000000000..7fe18d55d --- /dev/null +++ b/2018.11.26-leetcode11/Ostrichcrab.md @@ -0,0 +1,22 @@ +``` +class Solution { +public: + int max(int a, int b){return a>b?a:b;} + int min(int a, int b){return a& height) { + int ans = 0; + int l = 0, r = height.size() - 1; + ans = max(ans,min(height[l],height[r])*(r-l)); + while(lheight[r]){ + r--; + ans = max(ans,min(height[l],height[r])*(r-l)); + }else{ + l++; + ans = max(ans,min(height[l],height[r])*(r-l)); + } + } + return ans; + } +}; +``` diff --git a/2018.11.26-leetcode11/Tony the Cyclist.md b/2018.11.26-leetcode11/Tony the Cyclist.md new file mode 100644 index 000000000..bbf9e92b3 --- /dev/null +++ b/2018.11.26-leetcode11/Tony the Cyclist.md @@ -0,0 +1,45 @@ +## Java + +``` +class Solution { + public int maxArea(int[] height) { + int l = 0, r = height.length - 1; + int s = (r-l) * (height[l] > height[r]? height[r]: height[l]); + while (l < r){ + if (height[l] < height[r]){ + l++; + } + else { + r--; + } + s = Math.max(s, (r-l) * (height[l] > height[r]? height[r]: height[l])); + } + return s; + + } +} +``` + + + +## Python +``` +class Solution(object): + def maxArea(self, height): + """ + :type height: List[int] + :rtype: + """ + l = 0 + r = len(height) - 1 + h = (height[r] if (height[l] > height[r]) else height[l]) + s = h * (r - l) + while l < r: + if height[l] > height[r]: + r -= 1 + else: + l += 1 + h = (height[r] if (height[l] > height[r]) else height[l]) + s = max(s, (r-l)*h) + return s +``` diff --git a/2018.11.26-leetcode11/kiritocly.md b/2018.11.26-leetcode11/kiritocly.md new file mode 100644 index 000000000..3ee9a6715 --- /dev/null +++ b/2018.11.26-leetcode11/kiritocly.md @@ -0,0 +1,29 @@ + + + private static int solution(int[] array) { + //从左右两边同时遍历,每次都舍弃最短边 + int left = 0; + int right = array.length - 1; + int resultTemp = 0; + int result = 0; + while (left < right) { + if (array[left] <= array[right]) { + //左边柱子低于右边 + //计算临时盛水容量 + resultTemp = array[left] * (right - left); + //矮柱子向中间移动 + left++; + } else if (array[left] >= array[right]) { + //左边柱子高于右边 + //计算临时盛水容量 + resultTemp = array[right] * (right - left); + //矮柱子向中间移动 + right--; + } + //判断临时盛水容量 + if (resultTemp > result) { + result = resultTemp; + } + } + return result; + } diff --git a/2018.11.26-leetcode11/str818.md b/2018.11.26-leetcode11/str818.md new file mode 100644 index 000000000..d80ab9a94 --- /dev/null +++ b/2018.11.26-leetcode11/str818.md @@ -0,0 +1,24 @@ +# 乘最多水的容器 + +[题目描述](https://leetcode-cn.com/problems/container-with-most-water/description/):给定 n 个非负数 a1,a2,...,an,每个数代表坐标中的一个点 (i,ai)。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i,ai) 和 (i,0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 + +**示例:** +``` +输入: [1,8,6,2,5,4,8,3,7] +输出: 49 +``` + +**解题思路:** 两线段之间形成的区域总是会受到其中较短那条长度的限制,同时,两线段距离越远,得到的面积就越大。使用两个指针,一个放在开始,一个放在末尾,更新存储的最大面积,将指向较短线段的指针向较长线段那端移动一步。 + +```java +public int maxArea(int[] height) { + int start = 0,end = height.length - 1; + int maxArea = 0; + while(end > start){ + maxArea = Math.max(maxArea, Math.min(height[start], height[end]) * (end - start)); + if(height[start] > height[end]) end--; + else start++; + } + return maxArea; +} +``` diff --git a/2018.11.26-leetcode11/syuan.md b/2018.11.26-leetcode11/syuan.md new file mode 100644 index 000000000..9534da05a --- /dev/null +++ b/2018.11.26-leetcode11/syuan.md @@ -0,0 +1,39 @@ +##### 题目 + +``` +给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 + +说明:你不能倾斜容器,且 n 的值至少为 2。 +``` +![微信截图_20181127122321](2DF0C29B574D4A30BFAB06ABDF185FA9) +``` +图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。 +示例: + +输入: [1,8,6,2,5,4,8,3,7] +输出: 49 +``` +##### 思路 +双指针 + +##### 代码 + +``` +class Solution { + public int maxArea(int[] height){ + int maxarea=0; + int i=0; + int j=height.length-1; + + while(i +#include +using namespace std; + +//mysol: + int removeDuplicates(vector& nums) { + for (int i = 1; i < nums.size(); i++) { + if (nums[i] == nums[i-1]) + nums.erase(nums.begin() + i); + } + return nums.size(); + } +//better sol: + int removeDuplicates(vector& nums) { + int i = 0; + for (int j = 1; j < nums.size(); j++) { + if (nums[i] != nums[j]) { + i++; + nums[i] = nums[j]; + } + } + return i + 1; + } +``` diff --git "a/2018.11.26-leetcode11/\343\200\202\343\200\202\343\200\202.md" "b/2018.11.26-leetcode11/\343\200\202\343\200\202\343\200\202.md" new file mode 100644 index 000000000..26ea7d0fd --- /dev/null +++ "b/2018.11.26-leetcode11/\343\200\202\343\200\202\343\200\202.md" @@ -0,0 +1,12 @@ + public int maxArea(int[] height) { + int left=0,right=height.length-1,area = 0; + while (left < right){ + area = Math.max(area,(right-left)*Math.min(height[left],height[right])); + if (height[left] < height[right]){ + left++; + }else { + right--; + } + } + return area; + } diff --git "a/2018.11.26-leetcode11/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.11.26-leetcode11/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..6bb4f2be6 --- /dev/null +++ "b/2018.11.26-leetcode11/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,27 @@ +``` +class Solution { + public int maxArea(int[] height) { + int left=0;//从左边遍历 + int right=height.length-1;//从右边遍历 + int tempCha=0; + int sum=0; + int tempsum=0; + while(leftheight[left]){ + tempsum=height[left]*tempCha; //短(短板)的边作为高,求出此时的面积 + left++; + }else{ + tempsum=height[right]*tempCha; + right--; + } + if(tempsum>sum){ + sum=tempsum; + } + + + } + return sum; + } +} +``` diff --git "a/2018.11.26-leetcode11/\345\256\266.md" "b/2018.11.26-leetcode11/\345\256\266.md" new file mode 100644 index 000000000..fde8ca303 --- /dev/null +++ "b/2018.11.26-leetcode11/\345\256\266.md" @@ -0,0 +1,16 @@ +``` +func maxArea(height []int) int { + l := len(height)-1 + max,now := 0,0 + for a:=0;a= height[l] { + now = height[l] * (l-a) + l-- + }else { + now = height[a] * (l-a) + a++ + } + if now > max {max = now} + } + return max +} diff --git "a/2018.11.26-leetcode11/\346\232\256\346\210\220\351\233\252.md" "b/2018.11.26-leetcode11/\346\232\256\346\210\220\351\233\252.md" new file mode 100644 index 000000000..e8291a22e --- /dev/null +++ "b/2018.11.26-leetcode11/\346\232\256\346\210\220\351\233\252.md" @@ -0,0 +1,22 @@ +class Solution { + public int maxArea(int[] height) { + if( height.length < 2 ){ + return 0; + } + //双指针,复杂度O(n),5ms 91% + int max=0; + int i=0; + int j= height.length-1; + while(i < j){ + int areaTmp= (j-i) * Math.min(height[i] , height[j]); + Boolean flag = height[i] > height[j] ? true : false; + if(max < areaTmp){ + max = areaTmp; + } + if(flag == true){ + j--; + }else{ + i++; + } + } +} diff --git "a/2018.11.26-leetcode11/\347\247\215\350\212\261\345\256\266\347\232\204\351\204\202\345\205\224.md" "b/2018.11.26-leetcode11/\347\247\215\350\212\261\345\256\266\347\232\204\351\204\202\345\205\224.md" new file mode 100644 index 000000000..977ebd09e --- /dev/null +++ "b/2018.11.26-leetcode11/\347\247\215\350\212\261\345\256\266\347\232\204\351\204\202\345\205\224.md" @@ -0,0 +1,26 @@ +``` +public class Main { + + public static void main(String[] args) { + int[] height = {2,3,10,5,7,8,9}; + System.out.println(new Solution().maxArea(height)); + } +} + +public class Solution{ + public int maxArea(int[] height){ + int low = 0; + int high = height.length-1; + int max_area=0; + while (low < high){ + int min_height = height[low]array[right]){ + temparea=array[right]*len; + right--; + }else { + temparea=array[left]*len; + left++; + } + if(temparea>result){ + result=temparea; + } + } + return result; + } + + public static void main(String[] args) { + Solution1 s1 = new Solution1(); + int[] a = {1,8,6,2,5,4,8,3,7}; + int b = s1.MaxArea(a); + System.out.println("盛最多水的容器面积是:"+b); + } +} diff --git "a/2018.11.26-leetcode11/\351\273\216\346\230\216\345\210\235\351\206\222.md" "b/2018.11.26-leetcode11/\351\273\216\346\230\216\345\210\235\351\206\222.md" new file mode 100644 index 000000000..34f38cb36 --- /dev/null +++ "b/2018.11.26-leetcode11/\351\273\216\346\230\216\345\210\235\351\206\222.md" @@ -0,0 +1,23 @@ +``` +class Solution { + public int maxArea(int[] height) { + int i=0,j=height.length-1; + int V=0,V1; + while(i<=j) { + if(height[i]<=height[j]) { + V1 = (j-i)*height[i]; + i++; + } + else { + V1 = (j-i)*height[j]; + j--; + } + if(V1>=V) { + V = V1; + } + + } + return V; + } +} +``` diff --git a/2018.11.27-leetcode125/Avalon.md b/2018.11.27-leetcode125/Avalon.md new file mode 100644 index 000000000..94e7b21a9 --- /dev/null +++ b/2018.11.27-leetcode125/Avalon.md @@ -0,0 +1,30 @@ +class Solution { + public boolean isPalindrome(String s) { + if (s.length() == 0)//空字符串为回文串 + return true; + char[] chars = s.toCharArray(); + int len = chars.length; + List list1 = new ArrayList<>(); + for (int i= 0; i='a'&&chars[i]<='z'){//小写比大写更大 32 + list1.add(chars[i]); + }else if (chars[i]>='A'&&chars[i]<='Z'){ + list1.add((char)((int)chars[i]+32));//一句话转小写 + }else if (chars[i]>='0'&&chars[i]<='9'){ + list1.add(chars[i]); + } + } + int listlen = list1.size(); + if (listlen == 0) + return true; + boolean flag = true; + for (int i = 0; i < listlen /2 +1;i++){ + if (list1.get(i) != list1.get(listlen-1-i)){ + return false; + } + + } + return flag; + } +} diff --git a/2018.11.27-leetcode125/FFFro.md b/2018.11.27-leetcode125/FFFro.md new file mode 100644 index 000000000..e65e559e5 --- /dev/null +++ b/2018.11.27-leetcode125/FFFro.md @@ -0,0 +1,25 @@ +class Solution { + public boolean isPalindrome(String s) { + s = s.toLowerCase(); + char[] charArray = s.toCharArray(); + String res = ""; + for (int i = 0; i < charArray.length; i++) { + if ((int)charArray[i]>=48&&(int)charArray[i]<=57 || (int)charArray[i]>=97&&(int)charArray[i]<=122) + res+=charArray[i]; + } + char[] array = res.toCharArray(); + int start = 0; + int end = array.length-1; + while (end>start){ + + if(array[start] == array[end]){ + start++; + end--; + }else { + return false; + } + } + return true; + + } +} diff --git a/2018.11.27-leetcode125/Ostrichcrab.md b/2018.11.27-leetcode125/Ostrichcrab.md new file mode 100644 index 000000000..6d9d19bbd --- /dev/null +++ b/2018.11.27-leetcode125/Ostrichcrab.md @@ -0,0 +1,25 @@ +``` +class Solution { +public: + bool isPalindrome(string s) { + if(s.length()==0) return true; + string t = ""; + for(int i = 0; i < s.length(); i++){ + + if(s[i]>='a'&&s[i]<='z'){ + t += s[i]; + }else if(s[i]>='A'&&s[i]<='Z'){ + t += 'a' + s[i] - 'A'; + }else if(s[i]>='0'&&s[i]<='9'){ + t += s[i]; + } + } + string tt = t; + reverse(tt.begin(),tt.end()); + for(int i = 0; i < t.length(); i++){ + if(t[i]!=tt[i]) return false; + } + return true; + } +}; +``` diff --git a/2018.11.27-leetcode125/TheRocket.md b/2018.11.27-leetcode125/TheRocket.md new file mode 100644 index 000000000..af44b79cb --- /dev/null +++ b/2018.11.27-leetcode125/TheRocket.md @@ -0,0 +1,21 @@ +```java +class Solution { + + public boolean isPalindrome(String s) { + int i = 0; + int j = s.length() - 1; + while (i < j) { + while (i < j && !Character.isLetterOrDigit(s.charAt(i))) { + ++i; + } + while (i < j && !Character.isLetterOrDigit(s.charAt(j))) { + --j; + } + if (Character.toLowerCase(s.charAt(i++)) != Character.toLowerCase(s.charAt(j--))) { + return false; + } + } + return true; + } +} +``` diff --git a/2018.11.27-leetcode125/Tony the Cyclist.md b/2018.11.27-leetcode125/Tony the Cyclist.md new file mode 100644 index 000000000..394291e2e --- /dev/null +++ b/2018.11.27-leetcode125/Tony the Cyclist.md @@ -0,0 +1,9 @@ +``` +class Solution { + public boolean isPalindrome(String s) { + s = s.replaceAll("[ `~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&;*()\"——+|{}【】‘;:”“’。,、?|-]", "").toLowerCase(); + StringBuffer sb = new StringBuffer(s); + return sb.toString().equals(sb.reverse().toString()); + } +} +``` diff --git a/2018.11.27-leetcode125/WhiteNight.md b/2018.11.27-leetcode125/WhiteNight.md new file mode 100644 index 000000000..f605ea232 --- /dev/null +++ b/2018.11.27-leetcode125/WhiteNight.md @@ -0,0 +1,50 @@ +java + +/** + * 验证回文串 + * + */ +public class A7 { + public boolean isPalindrome(String s) { + if (s.isEmpty()) + return true; +​ + int begin = 0; + int end = s.length() - 1; +​ + char beginChar, endChar; +​ + while (begin <= end){ + beginChar = s.charAt(begin); + endChar = s.charAt(end); + if (!Character.isLetterOrDigit(beginChar)){ + begin++; + continue; + } + else if (!Character.isLetterOrDigit(endChar)){ + end--; + continue; + } + else { + if (Character.toLowerCase(beginChar) != Character.toLowerCase(endChar)) + return false; + else{ + begin++; + end--; + } + } + } +​ + return true; + } +​ + public static void main(String[] args) { + A7 a = new A7(); + String s1 = "A man, a plan, a canal: Panama"; + String s2 = "race a car"; + boolean res1 = a.isPalindrome(s1); + boolean res2 = a.isPalindrome(s2); + System.out.println(res1); + System.out.println(res2); + } +} diff --git a/2018.11.27-leetcode125/caroline.md b/2018.11.27-leetcode125/caroline.md new file mode 100644 index 000000000..d09724dce --- /dev/null +++ b/2018.11.27-leetcode125/caroline.md @@ -0,0 +1,25 @@ +题目详述 +大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。 +n<=39 +(这里的字体怎么调呀,要下什么插件吗,另外,斐波那契数列的第0项怎么是0,百科里面是1,这样婶儿的,斐波那契数列指的是这样一个 +数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368........) + +public class Solution{ + public int Fibonacci(int n){ + int a = 0; + int b =1; + if(n == 0) + return 1; + if(n == 1) + return 1; + int i=2; + int sum=0; + while(i<=n){ + sum = a+b; + a=b; + b=sum; + i++; + } + return sum; + } +} diff --git a/2018.11.27-leetcode125/cuiHlu.md b/2018.11.27-leetcode125/cuiHlu.md new file mode 100644 index 000000000..2a1b1bc35 --- /dev/null +++ b/2018.11.27-leetcode125/cuiHlu.md @@ -0,0 +1,21 @@ + //isalnum()判断是否为字母或者是数字 + bool isPalindrome(string s) { + int length = s.size(); + int start = 0; + int end = start + length - 1; + while (start <= end) + { + if (!isalnum(s[start])) + ++start; + else if (!isalnum(s[end])) + --end; + else + { + if (tolower(s[start]) != tolower(s[end])) + return false; + ++start; + --end; + } + } + return true; + } diff --git a/2018.11.27-leetcode125/halfofwater.md b/2018.11.27-leetcode125/halfofwater.md new file mode 100644 index 000000000..dc07943e2 --- /dev/null +++ b/2018.11.27-leetcode125/halfofwater.md @@ -0,0 +1,38 @@ +## leetcode 125 + +``` +class Solution { +public: + bool isPalindrome(string s) { + string::iterator it; + for (it = s.begin(); it != s.end(); it++) + { + //bool b1 = !(65 <= *it && *it <= 90); + //bool b2 = !(97 <= *it && *it <= 122); + //bool b3 = !(48 <= *it && *it <= 57); + + if (!(65 <= *it && *it<= 90) && !(97 <= *it && *it <= 122) && !(48 <= *it && *it <= 57)) + { + s.erase(it); + it--; + } + if (65 <= *it && *it <= 90) + { + *it += 32; + } + } + int len = s.size(); + int i = 0, j = len - 1; + while (i < j) + { + if (s[i] != s[j]) + { + return false; + } + i++; + j--; + } + return true; + } +}; +``` diff --git a/2018.11.27-leetcode125/kiritocly.md b/2018.11.27-leetcode125/kiritocly.md new file mode 100644 index 000000000..ac1693ab8 --- /dev/null +++ b/2018.11.27-leetcode125/kiritocly.md @@ -0,0 +1,34 @@ + private static boolean solution(String input) { + if (input == null || "".equals(input)) { + return true; + } + char[] inputCharArray = input.toCharArray(); + //定义两个指针,一个头指针一个尾指针 + int head = 0; + int tail = inputCharArray.length - 1; + //判断字母和数字字符的正则表达式 + String regex = "^[0-9a-zA-Z]$"; + while (head <= tail) { + String headStr = inputCharArray[head] + ""; + String tailStr = inputCharArray[tail] + ""; + if (headStr.matches(regex) && tailStr.matches(regex)) { + if (headStr.toLowerCase().equals(tailStr.toLowerCase())) { + //比较下一个字符 + head++; + tail--; + } else { + //如果未匹配则直接返回 + return false; + } + } else { + //如果比较的字符不为字母或数字则不比较 + if (!headStr.matches(regex)) { + head++; + } + if (!tailStr.matches(regex)) { + tail--; + } + } + } + return true; + } diff --git a/2018.11.27-leetcode125/sourcema.md b/2018.11.27-leetcode125/sourcema.md new file mode 100644 index 000000000..9548c477d --- /dev/null +++ b/2018.11.27-leetcode125/sourcema.md @@ -0,0 +1,20 @@ +# leetcode 125 + public static boolean isPalindrome(String s) { + if (s == null || s.length() == 0) { + return true; + } + String str = s.toLowerCase(); + int left=0,right=s.length()-1; + while (left < right) { + while (left < right && !Character.isDigit(str.charAt(left)) && !Character.isAlphabetic(str.charAt(left))) { + left++; + } + while (left < right && !Character.isDigit(str.charAt(right)) && !Character.isAlphabetic(str.charAt(right))) { + right--; + } + if (str.charAt(left++) != str.charAt(right--)) { + return false; + } + } + return true; + } diff --git a/2018.11.27-leetcode125/str818.md b/2018.11.27-leetcode125/str818.md new file mode 100644 index 000000000..4ece6d309 --- /dev/null +++ b/2018.11.27-leetcode125/str818.md @@ -0,0 +1,23 @@ +```java +public boolean isPalindrome(String s) { + if (s.isEmpty()) return true; + int head = 0, tail = s.length() - 1; + char cHead, cTail; + while(head <= tail) { + cHead = s.charAt(head); + cTail = s.charAt(tail); + if (!Character.isLetterOrDigit(cHead)) { + head++; + } else if(!Character.isLetterOrDigit(cTail)) { + tail--; + } else { + if (Character.toLowerCase(cHead) != Character.toLowerCase(cTail)) { + return false; + } + head++; + tail--; + } + } + return true; +} +``` diff --git a/2018.11.27-leetcode125/tongLuoWan.md b/2018.11.27-leetcode125/tongLuoWan.md new file mode 100644 index 000000000..0f3eb1544 --- /dev/null +++ b/2018.11.27-leetcode125/tongLuoWan.md @@ -0,0 +1,24 @@ +>leetcode 125. Valid Palindrome + +``` +class Solution { + + public boolean isPalindrome(String s) { + if(s.length()==0) + return true; + s=s.toLowerCase(); + int i = 0, j = s.length()- 1; + while (i2018.11.27号打卡 diff --git a/2018.11.27-leetcode125/zjukk.md b/2018.11.27-leetcode125/zjukk.md new file mode 100644 index 000000000..23568af19 --- /dev/null +++ b/2018.11.27-leetcode125/zjukk.md @@ -0,0 +1,37 @@ +``` +#include +#include + +using namespace std; + +class Solution { +public: + bool isPalindrome(string s) { + int l = 0, r = s.size() - 1; + bool flag = false; + while (l <= r) { + if (!isAlphaNum(s[l])) { + ++l; continue; + } + if (!isAlphaNum(s[r])) { + --r; continue; + } + if ((s[r] + 32 - 'a') % 32 != (s[l] + 32 - 'a') % 32) {flag = true; break;} + ++l; --r; + } + return !flag; + } + bool isAlphaNum(char c) { + if (c >= 'a' && c <= 'z') return true; + if (c >= 'A' && c <= 'Z') return true; + if (c >= '0' && c <= '9') return true; + return false; + } +}; + +int main() { + Solution s; + cout << s.isPalindrome("race a car"); + //A man, a plan, a canal: Panama +} +``` diff --git "a/2018.11.27-leetcode125/\343\200\202\343\200\202\343\200\202.md" "b/2018.11.27-leetcode125/\343\200\202\343\200\202\343\200\202.md" new file mode 100644 index 000000000..d31191b03 --- /dev/null +++ "b/2018.11.27-leetcode125/\343\200\202\343\200\202\343\200\202.md" @@ -0,0 +1,30 @@ +``` +public boolean isPalindrome(String s){ + if (s.length() >= 2){ + int left = 0,right = s.length()-1; + char leftChar,rightChar; + while (left <= right){ + leftChar = s.charAt(left);rightChar = s.charAt(right); + if (leftChar>='A'&&leftChar<='Z'){//转换大写字母为小写 + leftChar+=32; + }else if (rightChar>='A'&&rightChar<='Z'){ + rightChar+=32; + } + if (leftChar == rightChar){ + left++;right--; + continue; + } + //跳过非字母非数字的字符 + if (!((leftChar>='0'&& leftChar<='9') || (leftChar>='a'&&leftChar<='z') || (leftChar>='A'&&leftChar<='Z'))){ + left++; + continue; + }else if (!((rightChar>='0'&& rightChar<='9') || (rightChar>='a'&&rightChar<='z') || (rightChar>='A'&&rightChar<='Z'))){ + right--; + continue; + } + if (leftChar != rightChar)return false; + } + } + return true; + } + ``` diff --git "a/2018.11.27-leetcode125/\345\210\230\346\266\246\346\263\275.md" "b/2018.11.27-leetcode125/\345\210\230\346\266\246\346\263\275.md" new file mode 100644 index 000000000..5e95edf1b --- /dev/null +++ "b/2018.11.27-leetcode125/\345\210\230\346\266\246\346\263\275.md" @@ -0,0 +1,49 @@ +## 判断字符串是否为回文字符串 + +> lanague: java + +> vsersion: jdk1.7 + +``` +public static boolean isPalindrome(String s) { + s = s.replaceAll("[^0-9a-zA-Z\u4e00-\u9fa5]+","").toLowerCase(); + System.out.println(s); + char[] chars = s.toCharArray(); + if (chars.length==0){ + return false; + } + if (chars.length==1){ + return true; + } + for (int i=0;i 输出结果 + +>raceacar + +>false + +>amanaplanacanalpanama + +>true + + + + + + + + diff --git "a/2018.11.27-leetcode125/\345\217\245\345\255\220.java" "b/2018.11.27-leetcode125/\345\217\245\345\255\220.java" new file mode 100644 index 000000000..2da595f71 --- /dev/null +++ "b/2018.11.27-leetcode125/\345\217\245\345\255\220.java" @@ -0,0 +1,36 @@ +package Leetcode; + +public class for125 { + public boolean isPalindrome(String s) { + if(s.length()==0) + return true; + //s=s.toLowerCase(); + char[] cs =s.toCharArray(); + int i = 0, j = cs.length - 1; + while(i64&&cs[j]>64&&Math.abs(cs[i]-cs[j])==32)){ + i++; + j--; + } + else + return false; + + } + return true; + } + public static void main(String[] args) { + // TODO Auto-generated method stub + String reg="[^a-zA-Z0-9]"; + String s = "A man, a plan, a canal: Panama"; + char x ='A'; + x=Character.toLowerCase(x); + s=s.toLowerCase(); + System.out.println(x); + } + +} diff --git "a/2018.11.27-leetcode125/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.11.27-leetcode125/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..82d6547e8 --- /dev/null +++ "b/2018.11.27-leetcode125/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,37 @@ +``` +class Solution { + public boolean isPalindrome(String s) { + s = s.toLowerCase(); + char [] charArray = s.toCharArray(); + + int begin = 0; + int end = charArray.length - 1; + while(begin < end) + + { + if (!isChar(charArray[begin])){//不是数字和小字母 + begin++; + continue; + } + if (!isChar(charArray[end])){//不是数字和小字母 + end--; + continue; + } + if(charArray[begin] == charArray[end]) + { + begin++; + end--; + }else{ + return false; + } + } + return true; + } + public boolean isChar(char c){//判断是否为数字或者字母 + if (c<48||(c>57&&c<65)||(c>90&&c<97)||c>122){ + return false; + } + return true; + } +} +``` diff --git "a/2018.11.27-leetcode125/\345\255\231\350\241\214\350\200\205.md" "b/2018.11.27-leetcode125/\345\255\231\350\241\214\350\200\205.md" new file mode 100644 index 000000000..037bb68bc --- /dev/null +++ "b/2018.11.27-leetcode125/\345\255\231\350\241\214\350\200\205.md" @@ -0,0 +1,30 @@ + +class Solution{ +private: + int top; + char elem[MAXSIZE]; +public: + void push_sq(char *arr[],Solution *sq){ + for(int i=0;itop=0; + } + void push(Solution *sq,char x){ + sq->elem[sq->top]=x; + sq->top++; + } + char pop(Solution *sq){ + return (sq->eelm[sq->--top]); + } +}; + diff --git "a/2018.11.27-leetcode125/\345\256\266.md" "b/2018.11.27-leetcode125/\345\256\266.md" new file mode 100644 index 000000000..4ee794c1f --- /dev/null +++ "b/2018.11.27-leetcode125/\345\256\266.md" @@ -0,0 +1,20 @@ +``` +func isPalindrome(s string) bool { + if len(s) <= 1 {return true} + low, hi := 0, len(s) - 1 + for low < hi { + for ; low < hi && !isValid(s[low]); low++ {} + for ; low < hi && !isValid(s[hi]); hi--{} + x, y := s[low], s[hi] + if (x >= 'A' && x <= 'Z') {x = x - 'A' + 'a'} + if (y >= 'A' && y <= 'Z') {y = y - 'A' + 'a'} + if x != y {return false} + low, hi = low+1, hi-1 + } + return true +} + +func isValid(b byte) bool { + return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') +} +``` diff --git "a/2018.11.27-leetcode125/\346\232\256\346\210\220\351\233\252.md" "b/2018.11.27-leetcode125/\346\232\256\346\210\220\351\233\252.md" new file mode 100644 index 000000000..9ea2883eb --- /dev/null +++ "b/2018.11.27-leetcode125/\346\232\256\346\210\220\351\233\252.md" @@ -0,0 +1,29 @@ +class Solution { + public boolean isPalindrome(String s) { + + s = s.replaceAll("[^a-zA-Z]", "").toLowerCase(); + s = s.toLowerCase(); + char [] charArray = s.toCharArray(); + String temp = ""; + for(int i=0;i= 48 && (int)charArray[i] <= 57) || ((int)charArray[i] >= 97 && (int)charArray[i] <= 122)) + { + temp += charArray[i]; + } + } + char [] resultArray = temp.toCharArray(); + int begin = 0;int end = resultArray.length - 1; + while(begin < end) + { + if(resultArray[begin] == resultArray[end]) + { + begin++; + end--; + }else{ + return false; + } + } + return true; + } +} diff --git "a/2018.11.27-leetcode125/\346\243\225\346\246\210\346\240\221.md" "b/2018.11.27-leetcode125/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..c37ae057d --- /dev/null +++ "b/2018.11.27-leetcode125/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,30 @@ + +public class TestisPalindrome { + public static boolean isPalindrome(String s){ + s = s.toLowerCase(); + char [] charArray = s.toCharArray(); + String temp = ""; + for(int i=0;i=60&&(int)charArray[i]<=71||(int)charArray[i]>=97&&(int)charArray[i]<=122){ + temp += charArray[i]; + } + } + char [] resultArray = temp.toCharArray(); + int begin = 0; + int end = resultArray.length-1; + while(begin= 'A' && ch <= 'Z') + { + ch += 32; + return true; + } + + if(ch >= 'a' && ch <= 'z') + return true; + + if(ch >= '0' && ch <= '9') + return true; + + return false; + } +}; diff --git "a/2018.11.27-leetcode125/\351\223\201\347\224\267\347\245\236sama.java" "b/2018.11.27-leetcode125/\351\223\201\347\224\267\347\245\236sama.java" new file mode 100644 index 000000000..96cd80151 --- /dev/null +++ "b/2018.11.27-leetcode125/\351\223\201\347\224\267\347\245\236sama.java" @@ -0,0 +1,12 @@ +char[] charArray = s.toCharArray(); + StringBuilder sb = new StringBuilder(); + for(char c:charArray){ + if(Character.isDigit(c)||Character.isLetter(c)){ + sb.append(c); + } + + } + + return sb.toString().toLowerCase().equals(sb.reverse().toString().toLowerCase()); + + } diff --git "a/2018.11.27-leetcode125/\351\223\201\347\224\267\347\245\236sama.md" "b/2018.11.27-leetcode125/\351\223\201\347\224\267\347\245\236sama.md" new file mode 100644 index 000000000..91888baef --- /dev/null +++ "b/2018.11.27-leetcode125/\351\223\201\347\224\267\347\245\236sama.md" @@ -0,0 +1,31 @@ +```Java +class Solution { + public boolean isPalindrome(String s) { + char[] charArray = s.toCharArray(); + int index=0; + for(char c:charArray){ + if(c>=65&&c<=90 ){ + charArray[index++]=c; + }else if(c>=97&&c<=122){ + charArray[index++]=(char)(c-32); + }else if(c>=48&&c<=57) { + charArray[index++]=c; + } + } + System.out.print(charArray); + int start=0; + int end=index-1; + while(start<=end){ + if(charArray[start]==charArray[end]){ + start++; + end--; + }else{ + return false; + } + + } + return true; + } +} +``` + diff --git a/2018.11.28 b/2018.11.28 new file mode 100644 index 000000000..40c2c6e7b --- /dev/null +++ b/2018.11.28 @@ -0,0 +1,32 @@ + +/** + * Created by zongjianwei + * DATE: 21:32 2018/11/28 + * Desc: 压缩字符数组 + */ +public class StringCompression { + public int compress(char[] chars){ + int m = 0; + int n = 0; + for(int i=0;in){ + for(int j=0;j<(""+(i-n+1)).toCharArray().length;j++){ + chars[m++] = chars[j]; + } + } + n = i +1; + } + } + return m; + } + + public static void main(String[] args) { + char[] chars = {'a','a','b','b','c','c','c'}; + StringCompression sc = new StringCompression(); + int length = sc.compress(chars); + System.out.println(length); + + } +} diff --git a/2018.11.28-leetcode151/-.md b/2018.11.28-leetcode151/-.md new file mode 100644 index 000000000..47c11b099 --- /dev/null +++ b/2018.11.28-leetcode151/-.md @@ -0,0 +1,28 @@ +public class Solution { + public String reverseWords(String s) { + List list = new ArrayList<>(); + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c != ' ') { + buffer.append(c); + }else{ + if (buffer.length() != 0) { + list.add(buffer.toString()); + buffer.setLength(0); + } + } + } + if (buffer.length() != 0) { + list.add(buffer.toString()); + buffer.setLength(0); + } + for (int i = list.size(); i > 0; i--) { + if (buffer.length() != 0) { + buffer.append(" "); + } + buffer.append(list.get(i-1)); + } + return buffer.toString(); + } +} diff --git a/2018.11.28-leetcode151/018429.md b/2018.11.28-leetcode151/018429.md new file mode 100644 index 000000000..350c263a7 --- /dev/null +++ b/2018.11.28-leetcode151/018429.md @@ -0,0 +1,48 @@ +int top=0; +void push(char c,char* stack) +{ + stack[top++]=c; +} +char pop(char* stack) +{ + return stack[--top];//写入s1 +} +void reverseWords(char *s) { + int i=0,j=0,flag=0; + while(s[i]!='\0') i++; + char* stack = (char*)malloc(i); + char* s1 = (char*)malloc(i+1); + i--; + while(i>=0) + { + if(s[i]==' ') + { + while(top!=0)//如果栈不为空 + { + flag=1; + s1[j++]=pop(stack); + } + if(flag==1) + { + s1[j++]=' '; + flag=0;//重置flag + } + i--; + } + else + { + push(s[i--],stack); + } + } + if(s[++i]!=' ') + { + while(top!=0)//如果栈不为空 + s1[j++]=pop(stack); + s[j]=' '; + } + else + j--; + s1[j]='\0'; + s = strcpy(s,s1); + free(s1); +} diff --git a/2018.11.28-leetcode151/Avalon.md b/2018.11.28-leetcode151/Avalon.md new file mode 100644 index 000000000..8063fcb02 --- /dev/null +++ b/2018.11.28-leetcode151/Avalon.md @@ -0,0 +1,20 @@ +public static String reverseWords(String input){ + + String[] arr = input.trim().split("\\s+");//"\\s+" + int len = arr.length; + /* + String[] result = new String[len]; + for (int i = 0;i + +__说明__:
+* 无空格字符构成一个单词。 +* 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 +* 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 + +__进阶__:
+* 请选用C语言的用户尝试使用 O(1) 空间复杂度的原地解法。 +### 1.2 输入与输出 +输入: +* string &s:给定的字符串s + +输出: +* void:原地修改 +### 1.3 样例 +#### 1.3.1 样例1 +输入: "the sky is blue"
+输出: "blue is sky the" +## 2 思路描述与代码 +### 2.1 思路描述(反转法) +1. 先整体反转 +2. 按单词逐个反转 + +比如输入: "the sky is blue"
+整体反转后为"elub si yks eht"
+按单词逐个反转后为"blue is sky the"
+### 2.2 代码 +```cpp +void reverseWords(string &s) { + //强行头部加空格方便统一处理 + s.insert(0, 1, ' '); + reverse(s.begin(), s.end()); + int len = s.size(); + //搜索的位置 + int search = 0; + //搜索的当前单词的长度 + int cnt_word = 0; + //搜索的当前单词的起始位置 + int start_word = 0; + while( search < len ){ + //在单词有效范围内 + if(s[search] != ' ') ++search, ++cnt_word; + //在单词边界 + else{ + if(cnt_word != 0){ + //翻转单词 + reverse(s.begin() + start_word, s.begin() + start_word + cnt_word); + //去除多余的空格 + search++; + while(search < len && s[search] == ' ') s.erase(s.begin() + search); + //设置下一个单词搜索的初始位置和长度 + start_word = search; + cnt_word = 0; + } + //可以去除原字符串中开头和尾巴可能存在的连续空格 + else s.erase(s.begin() + start_word); + } + } + //去除空格最后一个单词附带的空格 + s.pop_back(); +} +``` +## 3 思考与拓展 +### 3.1 思考 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +反转法|O(1)|O(n) +#### 3.1.3 难点分析 +1. 思路分析 +2. 原地修改 +### 3.2 拓展 +如果给你的是数组数据呢? diff --git a/2018.11.28-leetcode151/FFFro.md b/2018.11.28-leetcode151/FFFro.md new file mode 100644 index 000000000..404793a37 --- /dev/null +++ b/2018.11.28-leetcode151/FFFro.md @@ -0,0 +1,16 @@ +public class Solution { + public String reverseWords(String s) { + if(s == "") + return ""; + String[] str = s.split(" "); + String res = ""; + for (int i = str.length-1; i >=0; i--) { + if(!str[i].equals("")){ + if (res.length()>0) + res += " "; + } + res += str[i]; + } + return res; + } +} diff --git a/2018.11.28-leetcode151/GatesMa.md b/2018.11.28-leetcode151/GatesMa.md new file mode 100644 index 000000000..0efbf6870 --- /dev/null +++ b/2018.11.28-leetcode151/GatesMa.md @@ -0,0 +1,29 @@ +```cpp +class Solution { +public: + void reverseWords(string &s) { + if(s.empty()) + return ; + stringstream ss(s); + vector words; + string word; + while(ss>>word) + words.push_back(word+' '); + if(!words.empty()) + { + s.clear(); + + for(int i=words.size()-1;i>=0;i--) + { + s+= words[i]; + } + //s = s.substr(0,s.length()-1); + s.pop_back(); + } + else + { + s.clear(); + } + } +}; +``` diff --git a/2018.11.28-leetcode151/Istoryforever.md b/2018.11.28-leetcode151/Istoryforever.md new file mode 100644 index 000000000..56070c902 --- /dev/null +++ b/2018.11.28-leetcode151/Istoryforever.md @@ -0,0 +1,31 @@ +leetcode of 151 +``` +class Solution { +public: + void reverseWords(string &s) { + vector ans; + string t=""; + for(auto c = s.begin(); c!=s.end(); c++){ + if(*c ==' '){ + if(t != ""){ + ans.push_back(t); + t=""; + } + continue; + } + t+=*c; + if(c == s.end()-1){ + ans.push_back(t); + } + } + reverse(ans.begin(),ans.end()); + s=""; + for (auto i = ans.begin();i != ans.end(); i++){ + if(i == ans.begin()) s=*i; + else{ + s+=" "+*i; + } + } + } +}; +``` diff --git a/2018.11.28-leetcode151/Ostrichcrab.md b/2018.11.28-leetcode151/Ostrichcrab.md new file mode 100644 index 000000000..7b897dd54 --- /dev/null +++ b/2018.11.28-leetcode151/Ostrichcrab.md @@ -0,0 +1,36 @@ +``` +class Solution { +public: + void reverseWords(string &s) { + s.insert(0,1,' '); + reverse(s.begin(),s.end()); + int len = s.size(); + int now = 0; + int pos = 0; + int sum = 0; + while(now < len){ + + if(s[now]!=' '){ + now++; + sum++; + }else{ + + if(sum != 0){ + reverse(s.begin()+pos,s.begin()+pos+sum); + now++; + while(now str; + string s1; + int i=0; + while(i= 0) { + while (i >= 0 && chars[i] == ' ') { + --i; + } + if (i >= 0) { + int j = i; + while (i >= 0 && chars[i] != ' ') { + --i; + } + sb.append(chars, i + 1, j - i).append(' '); + --i; + } + } + if (sb.length() > 0) { + sb.setLength(sb.length() - 1); + } + return sb.toString(); + } +} +``` diff --git a/2018.11.28-leetcode151/Tony the Cyclist.md b/2018.11.28-leetcode151/Tony the Cyclist.md new file mode 100644 index 000000000..e5f497cb8 --- /dev/null +++ b/2018.11.28-leetcode151/Tony the Cyclist.md @@ -0,0 +1,26 @@ +``` +public class Solution { + public String reverseWords(String s) { + s = s.trim(); + System.out.println(s); + if (s.equals("")){ + return ""; + } + ArrayList ss = new ArrayList(Arrays.asList(s.split(" "))); + int len = ss.size(); + for (int i = 0; i < len; i++) { + if (ss.get(i).equals("")) { + ss.remove(i); + i--; + len--; + } + } + Collections.reverse(ss); + String result = ""; + for (String i : ss) { + result = result + i + " "; + } + return result.substring(0, result.length() - 1); + } +} +``` diff --git a/2018.11.28-leetcode151/V1ncentzzZ b/2018.11.28-leetcode151/V1ncentzzZ new file mode 100644 index 000000000..eaf5ab1da --- /dev/null +++ b/2018.11.28-leetcode151/V1ncentzzZ @@ -0,0 +1,14 @@ +public class Solution { + public String reverseWords(String s) { + StringBuilder result = new StringBuilder(); + if(s == null || s.length() == 0) return ""; + s = s.trim(); + String[] words = s.split(" "); + for(int i=words.length-1; i>=0; i--){ + if("".equals(words[i])) continue; + result.append(words[i]); + if(i > 0) result.append(" "); + } + return result.toString(); + } +} diff --git a/2018.11.28-leetcode151/WhiteNight.md b/2018.11.28-leetcode151/WhiteNight.md new file mode 100644 index 000000000..a788c6637 --- /dev/null +++ b/2018.11.28-leetcode151/WhiteNight.md @@ -0,0 +1,33 @@ +```java +/** + * 翻转字符串里面的单词 + * + */ +public class S2 { + public String reverseWords(String s) { + if (s == null || s.length() == 0) + return ""; + + String[] string = s.split(" "); + String res = ""; + + for (int i = string.length - 1; i >= 0; i--) { + if (!string[i].equals("")){ + if (res.length() > 0){ + res += " "; + } + res += string[i]; + } + } + + return res; + } + + public static void main(String[] args) { + S2 s = new S2(); + String string = "the sky is blue"; + String res = s.reverseWords(string); + System.out.println(res); + } +} +``` \ No newline at end of file diff --git a/2018.11.28-leetcode151/cuiHlu.md b/2018.11.28-leetcode151/cuiHlu.md new file mode 100644 index 000000000..d3d5877e4 --- /dev/null +++ b/2018.11.28-leetcode151/cuiHlu.md @@ -0,0 +1,26 @@ + //first reverse the string, second reverse the word + void reverseWords(string &s) { + if (s.empty()) + return; + reverse(s.begin(), s.end()); + int length = s.size(); + int storeIndex = 0; + for (int i = 0; i < length; ++i) + { + if (s[i] != ' ') + { + if (storeIndex != 0) + { + s[storeIndex++] = ' '; + } + int j = i; + while (j < length && s[j] != ' ' ) + { + s[storeIndex++] = s[j++]; + } + reverse(s.begin() + storeIndex - j + i, s.begin() + storeIndex); + i = j; + } + } + s.erase(s.begin() + storeIndex, s.end()); + } diff --git a/2018.11.28-leetcode151/disappo1nted.md b/2018.11.28-leetcode151/disappo1nted.md new file mode 100644 index 000000000..80b3ca6b5 --- /dev/null +++ b/2018.11.28-leetcode151/disappo1nted.md @@ -0,0 +1,18 @@ +public class Solution { + public String reverseWords(String s) { + if(s==null || s.length()==0){ + return""; + } + String[] array=s.split(" "); + String str=""; + for(int i = array.length-1;i>=0;--i){ + if(!array[i]equals("")){ + if(str.length()>0){ + str+=" "; + } + str+=array[i]; + } + } + return str; + } +} diff --git a/2018.11.28-leetcode151/halfodfwater.md b/2018.11.28-leetcode151/halfodfwater.md new file mode 100644 index 000000000..83622a87f --- /dev/null +++ b/2018.11.28-leetcode151/halfodfwater.md @@ -0,0 +1,58 @@ +## Leetcode 151 + +``` +class Solution { +public: + void reverseWords(string &s) { + + + vector res; + int head=0, tail=0; + + # 去掉首尾空格 + if(!s.empty()){ + s.erase(0,s.find_first_not_of(" ")); + s.erase(s.find_last_not_of(" ") + 1); + } + int len = s.size(); + int flag = 0; + int j=0; + for(int i=0;i=0;i--) + { + s += res[i]; + s += ' '; + } + s.erase(s.find_last_not_of(' ')+1); + } +}; + +``` + +## Performance: + +Beyond the 99.86% of commits. diff --git a/2018.11.28-leetcode151/ieei.md b/2018.11.28-leetcode151/ieei.md new file mode 100644 index 000000000..0b3f22190 --- /dev/null +++ b/2018.11.28-leetcode151/ieei.md @@ -0,0 +1,50 @@ +public class Solution { + public String reverseWords(String s) { + int length=s.length(); + //当字符串为空 + if(s == null){ return null;} + //当字符串为" "时 直接返回null + if(s.trim().equals("")){ + return s.trim(); + } + /** + * 先将字符串按照空格分裂为字符串数组 + * 然后收尾两个指针来交换即可 + */ + //0.掐头去尾 + String allRevStr=s.trim(); + //1.将字符串按照空格分裂为字符串数组 + String[] strChar=allRevStr.split(" "); + + //2.使用首尾两个指针来交换 + int left=0; + int right=strChar.length-1; + String temStr=null; + while(left= 0; i--) { + if (!splits[i].equals("")) { + //单词不为空 + result = result + splits[i]; + } + } + return result; + } diff --git a/2018.11.28-leetcode151/oven123.md b/2018.11.28-leetcode151/oven123.md new file mode 100644 index 000000000..d9c045cfc --- /dev/null +++ b/2018.11.28-leetcode151/oven123.md @@ -0,0 +1,39 @@ +###给定一个字符串,逐个翻转字符串中的每个单词。 +先整体利用Java语法,翻转整个字符,再一一翻转单词 +```java +public class Solution { + public String reverseWords(String s) { + int index = 0,n = s.length(); + StringBuilder sb = new StringBuilder(s).reverse();//翻转整个字符串 + for(int i = 0;i < n;i++){ + if(sb.charAt(i) != ' '){//如果遍历到的字符不是空格, + if(index != 0){//不是第一个单词 + sb.setCharAt(index, ' ');//加空格 + index++;//非空字符 + } + int j = i;//从当前遍历到字符开始 + while(j < n && sb.charAt(j) != ' '){ + sb.setCharAt(index,sb.charAt(j));//把该单词逐字复制到标记位置 + index++; + j++; + } + String t = new StringBuilder(sb.substring(index - (j - i),index)).reverse().toString();//将该单词翻转 + sb.replace(index - (j - i),index,t);//将翻转好的单词复制进去 + i = j;//将标记移动到该单词结束 + + } + } + sb.setLength(index);//防范空格情况 + return sb.toString(); +``` +大神解法: +```java +public class Solution { + public String reverseWords(String s) { + String[] words = s.trim().split(" +"); + Collections.reverse(Arrays.asList(words)); + return String.join(" ", words); + } +} +``` +把字符串切割为字符串数组,翻转,在单词间隔加入空格 diff --git a/2018.11.28-leetcode151/sourcema.md b/2018.11.28-leetcode151/sourcema.md new file mode 100644 index 000000000..ce03ad7e5 --- /dev/null +++ b/2018.11.28-leetcode151/sourcema.md @@ -0,0 +1,49 @@ +# LeetCode 151 + 1. public static String reverseWords(String s) {//first method + if (s.length() == 0 || s == null) { + return s; + } + String str = s.trim(); + String[] split = str.split(" +"); + String result = ""; + for (int i = split.length - 1; i >=0; i--) { + result += split[i] + " "; + } + return result.substring(0, result.length() - 1); + } + 2. public static String reverseWords2(String s) {//two method + if (s.length() == 0 || s == null) { + return s; + } + String str = s.trim();//" "此时str为"" + char[] chars = str.toCharArray(); + reverse(chars, 0, chars.length - 1); + //String target = new StringBuilder(str).reverse().toString(); + String result = ""; + int left=0,right=0; + //char[] chars = target.toCharArray(); + while (right < chars.length) { + while (right i){ + char t = c[i]; + c[i++] = c[j]; + c[j--] = t; + } + } +``` diff --git a/2018.11.28-leetcode151/syuan.md b/2018.11.28-leetcode151/syuan.md new file mode 100644 index 000000000..77db581f0 --- /dev/null +++ b/2018.11.28-leetcode151/syuan.md @@ -0,0 +1,127 @@ +##### 题目 +``` +给定一个字符串,逐个翻转字符串中的每个单词。 + +示例: + +输入: "the sky is blue", +输出: "blue is sky the". + +说明: + + 无空格字符构成一个单词。 + 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 + 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 + +进阶: 请选用C语言的用户尝试使用 O(1) 空间复杂度的原地解法。 +``` +##### 思路 +- 先将整个字符串反转 +- 按照空格分成String数组 +- 每个单词反转 +##### 代码 + +``` +public class Solution { + public String reverseWords(String s) { + int length=s.length(); + //当字符串为空 + if(s == null){ return null;} + //当字符串为" "时 直接返回null + if(s.trim().equals("")){ + return s.trim(); + } + + //1.反转整个字符串 + String allRevStr=ReverseWord(s); + //2.获得每个单词 + String[] strChar=allRevStr.split(" "); + + //3.反转每个字符串 + String reverse=""; + for (int i=0; i +#include +#include +#include +using namespace std; + +//using stack space O(n) +class Solution { +public: + void reverseWords(string &s) { + if (s.empty()) return; + stack st; + for (int i = 0; i < s.size(); ++i) { + string sub; + while (s[i] != ' ' && i < s.size()) { + sub.push_back(s[i++]); + } + if (!sub.empty()) st.push(sub);//空字符串因为有‘\0’的存在也会被当做一个元素放到stack中 + } + string res; + while (!st.empty()) { + res += st.top(); + res += " "; + st.pop(); + } + if (!res.empty()) res.pop_back(); + s = res; + } +}; + +class Solution2 { +public: + void reverseWords(string &s) { + istringstream is(s); + is >> s; + cout << s.size(); + string tmp; + while (is >> tmp) s = tmp + " " + s; + // if (!s.empty() && s[0] == ' ') s = ""; + } +}; +int main() { + Solution3 s; + // string str{"The sky is blue"}; + // string str{" "}; + string str{" The sky is blue"}; + // string str{"The sky is blue "}; + // string str{"The sky is blue"}; + s.reverseWords(str); + cout << str << "*"; +} +``` diff --git "a/2018.11.28-leetcode151/\343\200\202\343\200\202\343\200\202.md" "b/2018.11.28-leetcode151/\343\200\202\343\200\202\343\200\202.md" new file mode 100644 index 000000000..6b8feff93 --- /dev/null +++ "b/2018.11.28-leetcode151/\343\200\202\343\200\202\343\200\202.md" @@ -0,0 +1,29 @@ +``` +public String reverseWords(String s) { + int i = s.length()-1,wordRight=-1; + StringBuilder builder = new StringBuilder(); + while (i >= 0){ + if (s.charAt(i) == ' '){ + if (wordRight!=-1){ + if (builder.length()!=0){ + builder.append(' '); + } + builder.append(s.substring(i+1,wordRight+1)); + wordRight=-1; + } + i--; + continue; + } + if (wordRight==-1)wordRight = i; + i--; + } + //添加最后一个单词 + if (wordRight!=-1){ + if (builder.length()!=0){ + builder.append(' '); + } + builder.append(s.substring(i+1,wordRight+1)); + } + return builder.toString(); + } + ``` diff --git "a/2018.11.28-leetcode151/\344\270\215\350\203\275\345\220\203\345\244\252\351\245\261.md" "b/2018.11.28-leetcode151/\344\270\215\350\203\275\345\220\203\345\244\252\351\245\261.md" new file mode 100644 index 000000000..255de0e06 --- /dev/null +++ "b/2018.11.28-leetcode151/\344\270\215\350\203\275\345\220\203\345\244\252\351\245\261.md" @@ -0,0 +1,14 @@ +public class Solution { + public String reverseWords(String s) { + String[] ss=s.split(" "); + StringBuilder answer=new StringBuilder(); + for(int i=ss.length-1;i>=0;i--) { + ss[i]=ss[i].trim(); + if(!ss[i].equals("")&&ss[i]!=null) { + System.out.println(ss[i]); + answer.append(ss[i]+" "); + } + } + return answer.toString().trim(); + } +} diff --git "a/2018.11.28-leetcode151/\345\225\246\345\225\246\345\225\246.md" "b/2018.11.28-leetcode151/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..923f4ddf8 --- /dev/null +++ "b/2018.11.28-leetcode151/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,26 @@ +```java +public class Solution { + public String reverseWords(String s) { + if(s==null||s.length()<=0)return ""; + String res = ""; + int l,r; + l=s.length()-1; + while(l>=0&&s.charAt(l)==' ')l--; + if(l<0)return ""; + boolean flag = false; + while(l>=0){ + while(l>=0&&s.charAt(l)!=' ')l--; + for(r=l+1;r=0&&s.charAt(l)==' ')l--; + } + return res; + } +} +``` diff --git "a/2018.11.28-leetcode151/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.11.28-leetcode151/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..82f8c5168 --- /dev/null +++ "b/2018.11.28-leetcode151/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,20 @@ +``` + public class Solution { + public String reverseWords(String s) { + if (s == null || s.length() == 0) { + return ""; + } + String[] array = s.split(" ");//按照空格划分字符串 + String str = ""; + for (int i = array.length - 1; i >= 0; i--) { + if (!array[i].equals("")) { + if (str.length() > 0) { + str += " "; + } + str += array[i];//如果不是空字符串,就把截断的旧字符串添加到新字符串中。 + } + } + return str; + } +} +``` diff --git "a/2018.11.28-leetcode151/\345\246\256\345\217\257.md" "b/2018.11.28-leetcode151/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..a86f73238 --- /dev/null +++ "b/2018.11.28-leetcode151/\345\246\256\345\217\257.md" @@ -0,0 +1,53 @@ +```java +package sy181129; + +import java.util.Stack; + +/** + * @author suyuan + * + *给定一个字符串,逐个翻转字符串中的每个单词。 + + 示例: + + 输入: "the sky is blue", + 输出: "blue is sky the". + 说明: + + 无空格字符构成一个单词。 + 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 + 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 + */ +public class leetcode_151反转字符串里的单词 +{ + + public static void main(String[] args) + { + String string=" the sky is blue"; + System.out.println(reverseWords(string)); + + } + + public static String reverseWords(String s) { + String str=s.trim(); + if(str.equals("")) + return ""; + if(str.equals(" ")) + return ""; + Stack stack=new Stack<>(); + StringBuilder sb=new StringBuilder(); + String[] split = str.split("\\s+"); + for(String str1:split) + { + stack.push(str1); + } + int size=stack.size(); + for(int i=0;i= 0; ) + { + while (i >= 0 && s[i] == ' ') i--; + if (i < 0) break; + if (!rw.empty()) rw.push_back(' '); + string t; + while (i >= 0 && s[i] != ' ') t.push_back(s[i--]); //开始逆向输出 + reverse(t.begin(), t.end()); + rw.append(t); + } + s=rw; + } +}; diff --git "a/2018.11.28-leetcode151/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" "b/2018.11.28-leetcode151/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" new file mode 100644 index 000000000..bee775d9b --- /dev/null +++ "b/2018.11.28-leetcode151/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" @@ -0,0 +1,32 @@ +#leetcode151 +``` +public class Solution { + public String reverseWords(String s) { + if(s!=null&&"".equals(s)){ + return s; + }else if(s!=null){ + String[] ss=s.split(" "); + if(ss.length==0){ + return ""; + }else{ + String result=""; + for(int i=ss.length-1;i>=0;i--){ + if(i==ss.length-1){ + if(!ss[i].trim().equals("")){ + result+=ss[i].trim(); + } + + }else{ + if(!ss[i].trim().equals("")){ + result+=" "+ss[i].trim(); + } + } + + } + return result; + } + } + return s; + } +} +``` \ No newline at end of file diff --git "a/2018.11.28-leetcode151/\346\231\250\346\233\246\351\233\250\351\234\262.md" "b/2018.11.28-leetcode151/\346\231\250\346\233\246\351\233\250\351\234\262.md" new file mode 100644 index 000000000..47b9091cd --- /dev/null +++ "b/2018.11.28-leetcode151/\346\231\250\346\233\246\351\233\250\351\234\262.md" @@ -0,0 +1,17 @@ +public static String reverseWords(String str) { + str=str.trim(); + if(str.isEmpty()||str.length()==1||str.indexOf("\\s+")!=-1) { + return str; + } + StringBuffer sb = new StringBuffer(); + String[] str1=str.split("\\s+"); + for (int i = 0; i < str1.length; i++) { + if(i reverseWord = new Stack<>(); + StringBuffer sb = new StringBuffer(); + char[] datas = s.toCharArray(); + for(int i=0;i=0;i--){ + if(!array[i].equals("")){ + if(str.length()>0){ + str+=" "; + } + str += array[i]; + } + } + return str; + } + + public static void main(String[] args) { + String s = "hello world!"; + System.out.println(reverseWords(s)); + } +} diff --git "a/2018.11.28-leetcode151/\346\271\233\346\261\237\347\224\262\351\270\237.md" "b/2018.11.28-leetcode151/\346\271\233\346\261\237\347\224\262\351\270\237.md" new file mode 100644 index 000000000..9070b2973 --- /dev/null +++ "b/2018.11.28-leetcode151/\346\271\233\346\261\237\347\224\262\351\270\237.md" @@ -0,0 +1,17 @@ +``` +public static String reverseWords(String s) { + int len = s.length(); + int j = len; + String result = ""; + for (int i = len - 1; i >= 0; i--) { + if (s.charAt(i) == ' '){ + j = i ; + } else if (i == 0 || s.charAt(i - 1) == ' ') { + if (result.length() != 0) { + result += ' '; + } + result += s.substring(i, j); + } + } + return result; +} diff --git "a/2018.11.28-leetcode151/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.11.28-leetcode151/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..c1b1965d5 --- /dev/null +++ "b/2018.11.28-leetcode151/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,35 @@ +class Solution { +public: + void reverseWords(string &s) { + + int size = s.length(); + stack sta; + + int begin = 0; + int cur = begin; + while(cur < size) + { + while(cur=1;i--){ + if (ss[i].equals("")){ //句子中可能会有多余空格 + continue; + } + newS = newS+ss[i]+" "; + } + newS = newS+ss[0]; + System.out.println(newS); + return newS; + } diff --git "a/2018.11.28-leetcode151/\351\223\201\347\224\267\347\245\236sama.md" "b/2018.11.28-leetcode151/\351\223\201\347\224\267\347\245\236sama.md" new file mode 100644 index 000000000..0e6e6d6d6 --- /dev/null +++ "b/2018.11.28-leetcode151/\351\223\201\347\224\267\347\245\236sama.md" @@ -0,0 +1,58 @@ + +```java +public class Solution { + public String reverseWords(String s) { + StringBuilder sb = new StringBuilder(); + String[] sArray=new StringBuilder(s).reverse().toString().split(" "); + for(int i=0;i 0 && chars[i] != chars[i - 1])) { + String count = i - end == 1 ? "" : (i - end) + ""; + chars[length++] = chars[i - 1]; + for (int j = 0; j < count.length(); j++) { + chars[length++] = count.charAt(j); + } + end = i; + } + } + String count = chars.length - end == 1 ? "" : (chars.length - end) + ""; + chars[length++] = chars[chars.length - 1]; + for (int j = 0; j < count.length(); j++) { + chars[length++] = count.charAt(j); + } + return length; + } +} diff --git a/2018.11.29-leetcode443/Avalon.md b/2018.11.29-leetcode443/Avalon.md new file mode 100644 index 000000000..7fe154533 --- /dev/null +++ b/2018.11.29-leetcode443/Avalon.md @@ -0,0 +1,17 @@ +public static int compress(char[] chars) { + Map map = new LinkedHashMap(); + int len = chars.length; + for (int i = 0; i entry : map.entrySet()) { + num++; + if (!entry.getValue().equals("1")){ + num += entry.getValue().toCharArray().length ; + } + } + return num; + } diff --git a/2018.11.29-leetcode443/Be a fresh man.md b/2018.11.29-leetcode443/Be a fresh man.md new file mode 100644 index 000000000..722cd778a --- /dev/null +++ b/2018.11.29-leetcode443/Be a fresh man.md @@ -0,0 +1,104 @@ +## 443_(压缩字符串)String Compression +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定一组字符,使用原地算法将其压缩。
+压缩后的长度必须始终小于或等于原数组长度。
+数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。
+在完成原地修改输入数组后,返回数组的新长度。
+__注意__:
+所有字符都有一个ASCII值在[35, 126]区间内。 +1 <= len(chars) <= 1000。 +### 1.2 输入与输出 +输入: +* vector& chars:输入的字符列表 + +输出: +* int:原地压缩后的字符串的列表长度 +### 1.3 样例 +#### 1.3.1 样例1 +输入:
+["a","a","b","b","c","c","c"]
+输出:
+返回6,输入数组的前6个字符应该是:["a","2","b","2","c","3"]
+说明:
+"aa"被"a2"替代。"bb"被"b2"替代。"ccc"被"c3"替代。
+#### 1.3.2 样例2 +输入:
+["a"]
+输出:
+返回1,输入数组的前1个字符应该是:["a"]
+说明:
+没有任何字符串被替代。
+#### 1.3.3 样例2 +输入:
+["a","b","b","b","b","b","b","b","b","b","b","b","b"]
+输出:
+返回4,输入数组的前4个字符应该是:["a","b","1","2"]。
+说明:
+由于字符"a"不重复,所以不会被压缩。"bbbbbbbbbbbb"被“b12”替代。
+注意每个数字在数组中都有它自己的位置。 + +## 2 思路描述与代码 +### 2.1 思路描述(计数方法) +思路很清晰,这里就不举例了,思路采用计数方法。
+start 记录当前搜索字符的起始下标, search 记录当前搜索字符的遍历下标 , cnt_same_char 记录当前搜索字符的相同长度
+cmpr_len_char 记录当前压缩了的字符串的长度, len 记录输入字符串的长度
+```cpp +while( search < len ){ +  if(当前字符和前一个字符相同) cnt_same_char++; + else{ + 记录当前单词和数目 + start = search; + cnt_same_char = 1; + } + search++; +} +``` +### 2.2 代码 +```cpp +int compress(vector& chars) { + //强行添加空格方便统一处理 + chars.push_back(' '); + int len = chars.size(); + int start = 0, search = 1; + int cnt_same_char = 1, cmpr_len_char = 0; + while( search < len ){ + if(chars[search] == chars[search - 1]) ++cnt_same_char; + else{ + chars[cmpr_len_char++] = chars[start]; + //当前char计数值大于1时才压缩 + if(cnt_same_char > 1){ + //整形转字符串 + //从高位往低位转 遇见最高位后flag = 1; + int flag = 0; + int msb = 1000, cnt2char = cnt_same_char; + for( int i = 0; i < 4; i++ ){ + int weight = cnt2char / msb; + if(weight > 0 || flag) flag = 1, chars[cmpr_len_char++] = weight + '0'; + cnt2char = cnt2char % msb; + msb = msb / 10; + } + } + start = search; + cnt_same_char = 1; + } + search++; + } + //去除空格,恢复原始数据 + chars.pop_back(); + return cmpr_len_char; +} +``` +## 3 思考与拓展 +### 3.1 思考 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +计数方法|O(1)|O(n) +#### 3.1.3 难点分析 +1. 原地修改 +2. 整形数据转字符串 +### 3.2 拓展 +如果给你的数链表数据呢? diff --git a/2018.11.29-leetcode443/Decadence.md b/2018.11.29-leetcode443/Decadence.md new file mode 100644 index 000000000..edef5f25b --- /dev/null +++ b/2018.11.29-leetcode443/Decadence.md @@ -0,0 +1,67 @@ +题目地址:https://leetcode-cn.com/problems/string-compression/ + +leetcode 443 +给定一组字符,使用原地算法将其压缩。压缩后的长度必须始终小于或等于原数组长度。数组的每个元素应该是长度为1 的字符 +(不是 int 整数类型)。在完成原地修改输入数组后,返回数组的新长度。 +进阶: +你能否仅使用O(1) 空间解决问题? + +示例 1: +输入: +["a","a","b","b","c","c","c"] +输出: +返回6,输入数组的前6个字符应该是:["a","2","b","2","c","3"] +说明: +"aa"被"a2"替代。"bb"被"b2"替代。"ccc"被"c3"替代。 + +示例 2: +输入: +["a"] +输出: +返回1,输入数组的前1个字符应该是:["a"] +说明: +没有任何字符串被替代。 + +示例 3: +输入: +["a","b","b","b","b","b","b","b","b","b","b","b","b"] +输出: +返回4,输入数组的前4个字符应该是:["a","b","1","2"]。 +说明: +由于字符"a"不重复,所以不会被压缩。"bbbbbbbbbbbb"被“b12”替代。 +注意每个数字在数组中都有它自己的位置。 + +注意: + + 所有字符都有一个ASCII值在[35, 126]区间内。 + 1 <= len(chars) <= 1000。 + + +```$java +class Solution{ + public int compress(char[] chars){ + int n = chars.length; + int cur = 0; + for(int i =0;i 1) { + String a = String.valueOf(count); + for (int k = 0; k < a.length(); k++) { + chars[index++] = a.charAt(k); + } + } + count = 1; + } else { + count++; + } + } + return index; + } +} diff --git a/2018.11.29-leetcode443/GatesMa.md b/2018.11.29-leetcode443/GatesMa.md new file mode 100644 index 000000000..9a007d878 --- /dev/null +++ b/2018.11.29-leetcode443/GatesMa.md @@ -0,0 +1,47 @@ +# c++11 +```cpp +class Solution { +public: + int compress(vector& chars) { + vector c; + int num = 1; + string s; + char ch = chars[0]; + if(chars.size() == 1){ + return num; + } + for(vector::iterator it = chars.begin()+1;it != chars.end(); it++){ + if(ch != *it){ + c.push_back(ch); + if(num != 1){ + stringstream ss; + ss << num; + ss >> s; + int len = s.length(); + for(int i =0;i> s; + int len = s.length(); + + for(int i =0;i chars){ + int count=0; + char c1; + char c2; + for (int i = 0; i < chars.size()-1; i++) { + c1=chars.get(i); + count++; + c2=chars.get(i+1); + if(c1==c2){ + chars.remove(i); + i--; + }else{//不相等 + if(count>1){//添加新元素,如:'1','5'等 + if(count<10){ + }else if(count>=10&&count<100){ + chars.add(i+1,(char) (count/10%10+48)); + }else if(count>=100&&count<1000){ + chars.add(i+1,(char) (count/100+48)); + chars.add(i+1,(char) (count/10%10+48)); + }else if(count>=1000&&count<10000){ + chars.add(++i,(char) (count/1000+48)); + System.out.println(chars.get(i+1)); + chars.add(++i,(char) (count/100%10+48)); + chars.add(++i,(char) (count/10%10+48)); + } + chars.add(i+1,(char) (count%10+48)); + } + count=0; + } + } + count++; + if(count>1){ + if(count<10){ + }else if(count>=10&&count<100){ + chars.add((char) (count/10%10+48)); + }else if(count>=100&&count<1000){ + chars.add((char) (count/100+48)); + chars.add((char) (count/10%10+48)); + }else if(count>=1000&&count<10000){ + chars.add((char) (count/1000+48)); + chars.add((char) (count/100%10+48)); + chars.add((char) (count/10%10+48)); + } + chars.add((char) (count%10+48)); + count=0; + } + System.out.println(chars); + return chars.size(); + } + + //测试运行 + public static void main(String[] args) { + char[] c = new char[1200]; + c[0]='a'; + c[1]='c'; + c[2]='c'; + for (int i = 3; i < 1198; i++) { + c[i]='g'; + } + c[1198]='c'; + c[1199]='c'; + Vector chars= new Vector<>(); + for (int i = 0; i < c.length; i++) { + chars.add(c[i]); + } + int n= compress(chars); + System.out.println("新数组长度:"+n); + } + } diff --git a/2018.11.29-leetcode443/Istoryforever.md b/2018.11.29-leetcode443/Istoryforever.md new file mode 100644 index 000000000..41f3dbf6b --- /dev/null +++ b/2018.11.29-leetcode443/Istoryforever.md @@ -0,0 +1,32 @@ +//Leetcode of 443 +class Solution { +public: + int compress(vector& chars) { + stringstream s; + int count = 1; + // chars.push_back(0); + for(int i = 0;i < chars.size();i++){ + + if(i == 0){ + s<1){ + char[] num = String.valueOf((i-index)).toCharArray(); + for (int j=0;j& chars) { + int len = chars.size(); + if(len == 1) return chars.size(); + chars.push_back(' ');//统一一下 + len++; + int cnt = 1; + char pre = ' '; + pre = chars[0]; + for(int i = 1; i < len; i++){ + if(chars[i] == pre){ + chars.erase(chars.begin()+i); + i--; + len--; + cnt++; + } else if(cnt>1){ + stringstream ss; + string s; + ss<>s; + pre=chars[i]; + for(int j = 0; j < s.size(); j++){ + chars.insert(chars.begin()+i,s[j]); + i++; + len++; + } + cnt=1; + } + pre = chars[i]; + } + chars.pop_back();//最后去除 + return chars.size(); + } +}; +``` diff --git a/2018.11.29-leetcode443/Sagittarius.md b/2018.11.29-leetcode443/Sagittarius.md new file mode 100644 index 000000000..09d701296 --- /dev/null +++ b/2018.11.29-leetcode443/Sagittarius.md @@ -0,0 +1,26 @@ +``` +class Solution { +public: + int compress(vector& chars) { + int count=0; + int index=0; + for(int i=0;i 1) { + for (char c : Integer.toString(cnt).toCharArray()) { + chars[n++] = c; + } + } + } + return n; + } +} +``` diff --git a/2018.11.29-leetcode443/Tony the Cyclist.md b/2018.11.29-leetcode443/Tony the Cyclist.md new file mode 100644 index 000000000..3d97ffca1 --- /dev/null +++ b/2018.11.29-leetcode443/Tony the Cyclist.md @@ -0,0 +1,43 @@ +``` +class Solution { + public int compress(char[] chars) { + char base = chars[0]; + int count = 1; + int pos = 0; + for (int i = 1; i < chars.length; i++){ + if (base != chars[i]){ + base = chars[i]; + if (count == 1){ + chars[++pos] = base; + continue; + } + // 先计数再写入下一个值 + for (int j = 0; j < String.valueOf(count).length(); j++){ + chars[++pos] = String.valueOf(count).charAt(j); + } + count = 1; + chars[++pos] = base; + } + else {// base == chars[i] + count ++; + if (i == chars.length-1){ + if (count == 1){ + continue; + } + for (int j = 0; j < String.valueOf(count).length(); j++){ + chars[++pos] = String.valueOf(count).charAt(j); + } + + } + + } + + } + pos++; + //splitArray(chars, pos); + if (pos == 0) + return 1; + return pos; +} +} +``` diff --git a/2018.11.29-leetcode443/WhiteNight.md b/2018.11.29-leetcode443/WhiteNight.md new file mode 100644 index 000000000..77f64850c --- /dev/null +++ b/2018.11.29-leetcode443/WhiteNight.md @@ -0,0 +1,41 @@ +```java +/** + * 压缩字符串 + * + */ +public class S3 { + public int compress(char[] chars) { + int count = 1; + int index = 0; + + for (int i = 0; i < chars.length; i++) { + if (i + 1 == chars.length || chars[i] != chars[i+1]){ + chars[index++] = chars[i]; + if (count > 1){ + String temp = String.valueOf(count); + for (int j = 0; j < temp.length(); j++) { + chars[index++] = temp.charAt(j); + } + } + count = 1; + } + else + count++; + } + + return index; + } + + public static void main(String[] args) { + S3 s = new S3(); + char[] chars = {'a','b','b','b','b','b','b','b','b','b','b','b'}; + int res = s.compress(chars); + System.out.println(res); + + for (int i = 0; i < chars.length; i++) { + System.out.print(chars[i] + " "); + } + } +} +``` + diff --git a/2018.11.29-leetcode443/halfofwater.md b/2018.11.29-leetcode443/halfofwater.md new file mode 100644 index 000000000..ab5d26b52 --- /dev/null +++ b/2018.11.29-leetcode443/halfofwater.md @@ -0,0 +1,59 @@ +## Leetcode 443 + +``` +class Solution { +public: + int compress(vector& chars) { + + if (chars.size() <= 1) return chars.size(); + + vector::iterator it = chars.begin(); + ++it; + int count = 1; + char tmp = chars[0]; + + char ccc = *(chars.end() - 1); + while (it < chars.end()) + { + if (*it == tmp) + { + + ++count; + if (it == chars.end() - 1) { + if (count != 1) { + + string s = to_string(count); + for (char c : s) { + it = chars.insert(it, c); + ++it; + } + it = chars.erase(it); + } + //++it; + } + else { + it = chars.erase(it); + } + } + else + { + if (count != 1) + { + string s = to_string(count); + for (char c : s) + { + it = chars.insert(it, c); + ++it; + } + } + + tmp = *it; + count = 1; + ++it; + } + } + return chars.size(); + } +}; + +``` diff --git a/2018.11.29-leetcode443/kiritocly.md b/2018.11.29-leetcode443/kiritocly.md new file mode 100644 index 000000000..9ed7a4ca1 --- /dev/null +++ b/2018.11.29-leetcode443/kiritocly.md @@ -0,0 +1,31 @@ + private static int solution(char[] charArray) { + if (charArray.length == 0) { + return 0; + } + //遍历整个字符数组 + //压缩后的字符长度 + int resultCount = 0; + //当前重复字符计数 + int count = 1; + for (int i = 0; i < charArray.length; i++) { + //如果遇到某个字符与当前字符不相等或者已经遍历到最后一个字符 + if (i + 1 == charArray.length || charArray[i] != charArray[i + 1]) { + //记录一下当前字符,并且resultCount加1,比如a,a,b,b,b,扫面到第二个a时 + //a!=b,如果a的个数大于1,先将a后面所有的a替换为数字,如a,a替换为a,2 + charArray[resultCount++] = charArray[i]; + if (count > 1) { + String temp = String.valueOf(count); + for (int k = 0; k < temp.length(); k++) { + charArray[resultCount++] = temp.charAt(k); + } + } + //重新统计下一个字符 + count = 1; + } else { + //统计重复的字符个数 + count++; + } + + } + return resultCount; + } diff --git a/2018.11.29-leetcode443/oven123.md b/2018.11.29-leetcode443/oven123.md new file mode 100644 index 000000000..c3db542ca --- /dev/null +++ b/2018.11.29-leetcode443/oven123.md @@ -0,0 +1,28 @@ +```java +class Solution { + public int compress(char[] chars) { + int start = 0; + int end = 0; + //定义两指示字符的标识符 + for(int i = 0;i < chars.length;i++){ + if(i==chars.length-1||chars[i+1] != chars[i]){//如果不同或遍历到最后一个 + chars[start] = chars[end];//在前一个字符计数后记录字母 + start++; + if(end < i){//当前指示位置与遍历位置不一致 + int sum = i-end+1;//对重复计数 + if(sum < 10){ + chars[start++] =(char)(sum+ '0'); + }else{ + chars[start++]=(char)(sum/10+ '0'); + chars[start] = (char)(sum % 10+ '0'); + start++; + } + } + end = i + 1;//保证遍历位置与标记位置相同 + } + } + return start; + + } +} +``` diff --git a/2018.11.29-leetcode443/sourcema.md b/2018.11.29-leetcode443/sourcema.md new file mode 100644 index 000000000..d52759317 --- /dev/null +++ b/2018.11.29-leetcode443/sourcema.md @@ -0,0 +1,29 @@ +# LeetCode 443 + class Solution { + public int compress(char[] chars) { + if (chars == null || chars.length == 0) { + return 0; + } + StringBuilder sb = new StringBuilder(); + int num=1; + for (int i = 0,j=0; i =s.length()?0:s.charAt(i); + } + return sb.toString().length(); + } +} diff --git a/2018.11.29-leetcode443/str818.md b/2018.11.29-leetcode443/str818.md new file mode 100644 index 000000000..d49d6e855 --- /dev/null +++ b/2018.11.29-leetcode443/str818.md @@ -0,0 +1,64 @@ +# 压缩字符串 + +【 [英文练习](https://leetcode.com/problems/string-compression/description/) | [中文练习](https://leetcode-cn.com/problems/string-compression/description/) 】 + +**题目描述:** 给定一组字符,使用原地算法将其压缩。压缩后的长度必须始终小于或等于原数组长度,数组的每个元素应该是长度为 1 的字符(不是 int 整数类型),在完成原地修改输入数组后,返回数组的新长度。 + +**示例 1:** +``` +输入: +["a","a","b","b","c","c","c"] + +输出: +返回6,输入数组的前6个字符应该是:["a","2","b","2","c","3"] + +说明: +"aa"被"a2"替代。"bb"被"b2"替代。"ccc"被"c3"替代。 +``` +**示例 2:** +``` +输入: +["a"] + +输出: +返回1,输入数组的前1个字符应该是:["a"] + +说明: +没有任何字符串被替代。 +``` +**示例 3:** +``` +输入: +["a","b","b","b","b","b","b","b","b","b","b","b","b"] + +输出: +返回4,输入数组的前4个字符应该是:["a","b","1","2"]。 + +说明: +由于字符"a"不重复,所以不会被压缩。"bbbbbbbbbbbb"被“b12”替代。 +注意每个数字在数组中都有它自己的位置。 +``` + +**说明:** +* 所有字符都有一个ASCII值在[35, 126]区间内。 +* 1 <= len(chars) <= 1000。 + +**解题思路:** 用双指针的思想,一个指针从前向后读字符,一个指针从前向后写字符,再通过一个指针记录相同字符序列中的第一个字符下标,用来计算相同字符的数量。 + +```java +public int compress(char[] chars) { + int anchor = 0, write = 0; + for (int read = 0; read < chars.length; read++) { + if (read + 1 == chars.length || chars[read + 1] != chars[read]) { + chars[write++] = chars[anchor]; + if (read > anchor) { + for (char c: ("" + (read - anchor + 1)).toCharArray()) { + chars[write++] = c; + } + } + anchor = read + 1; + } + } + return write; +} +``` diff --git a/2018.11.29-leetcode443/syuan.md b/2018.11.29-leetcode443/syuan.md new file mode 100644 index 000000000..a1dc97366 --- /dev/null +++ b/2018.11.29-leetcode443/syuan.md @@ -0,0 +1,79 @@ +##### 题目 +``` +给定一组字符,使用原地算法将其压缩。 + +压缩后的长度必须始终小于或等于原数组长度。 + +数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。 + +在完成原地修改输入数组后,返回数组的新长度。 +``` +##### 思路 +设置两个指针i 和 j +i是赋值指针 +j用来统计每次字符出现的次数 + +**难点** +当次数为两位数时的写入 + +``` +char[] temArray=String.valueOf(count).toCharArray(); +int k=0; +while (k& chars) { + int N = chars.size(); + int idx = 0, cnt = 0; + + for(int i = 0; i < N; ++i) { + cnt++; + if (i == N-1 || chars[i] != chars[i+1]) { + chars[idx++] = chars[i]; + if (cnt > 1) { + for(auto c : to_string(cnt)) + chars[idx++] = c; + } + cnt = 0; + } + } + return idx; + } +}; +``` diff --git "a/2018.11.29-leetcode443/\343\200\201Mr\343\200\202oh\357\274\201.md" "b/2018.11.29-leetcode443/\343\200\201Mr\343\200\202oh\357\274\201.md" new file mode 100644 index 000000000..80c178869 --- /dev/null +++ "b/2018.11.29-leetcode443/\343\200\201Mr\343\200\202oh\357\274\201.md" @@ -0,0 +1,32 @@ +public int compress(char[] chars) { + if (chars == null || chars.length == 0) { + return 0; + } + int count = 1; + char pre = chars[0]; + StringBuilder sb = new StringBuilder(); + + for (int i = 1; i < chars.length; i++) { + if (pre == chars[i]) { + count++; + }else { + if (count > 1) { + sb.append(pre); + sb.append(count); + } else if (count == 1) { + sb.append(pre); + } + pre = chars[i]; + count = 1; + } + } + sb.append(pre); + if (count > 1) { + sb.append(count); + } + int i=0; + for (char c : sb.toString().toCharArray()) { + chars[i++] = c; + } + return sb.length(); + } diff --git "a/2018.11.29-leetcode443/\343\200\202V1ncentzzZ.md" "b/2018.11.29-leetcode443/\343\200\202V1ncentzzZ.md" new file mode 100644 index 000000000..78b99e3a8 --- /dev/null +++ "b/2018.11.29-leetcode443/\343\200\202V1ncentzzZ.md" @@ -0,0 +1,30 @@ + // TODO 执行比较慢,有冗余代码,待优化 7ms + public int compress(char[] chars) { + if(chars.length == 0) return 0; + char temp = chars[0]; + int count = 0; + int len = 0; + for(int i=0; i 1){ + char[] step = String.valueOf(count).toCharArray(); + chars[len++] = step[0]; + if(count > 9) chars[len++] = step[1]; + } + temp = chars[i]; + count = 1; + } + if(i == chars.length - 1) { + chars[len++] = temp; + if(count > 1){ + char[] step = String.valueOf(count).toCharArray(); + chars[len++] = step[0]; + if(count > 9) chars[len++] = step[1]; + } + continue; + } + } + return len; + } diff --git "a/2018.11.29-leetcode443/\343\200\202\343\200\202\343\200\202.md" "b/2018.11.29-leetcode443/\343\200\202\343\200\202\343\200\202.md" new file mode 100644 index 000000000..21feabaf2 --- /dev/null +++ "b/2018.11.29-leetcode443/\343\200\202\343\200\202\343\200\202.md" @@ -0,0 +1,28 @@ + ``` + public int compress(char[] chars) { + int cur = 1;//压缩后字符串的长度 + int repet = 1; + for (int i = 1; i < chars.length; i++){ + if (chars[i-1] == chars[i]) {//出现连续重复的字符串 + repet++; + }else { + if (repet!=1){ + char[] num = String.valueOf(repet).toCharArray(); + for (int j = 0; j < num.length; j++){ + chars[cur++] = num[j]; + } + repet=1; + } + chars[cur++] = chars[i]; + } + } + if (repet!=1){ + char[] num = String.valueOf(repet).toCharArray(); + for (int j = 0; j < num.length; j++){ + chars[cur++] = num[j]; + } + } + Log.d(new String(chars)); + return cur; + } + ``` diff --git "a/2018.11.29-leetcode443/\344\270\200\346\260\247\345\214\226\344\272\214\351\222\222.md" "b/2018.11.29-leetcode443/\344\270\200\346\260\247\345\214\226\344\272\214\351\222\222.md" new file mode 100644 index 000000000..dc22f2444 --- /dev/null +++ "b/2018.11.29-leetcode443/\344\270\200\346\260\247\345\214\226\344\272\214\351\222\222.md" @@ -0,0 +1,27 @@ + +class Solution(object): + def compress(self, chars): + """ + :type chars: List[str] + :rtype: int + """ + + n = len(chars) + cnt = 1; + i = 0; + for j in range(1, len(chars)+1): + if j < n and chars[j-1] == chars[j]: + cnt += 1; + else: + chars[i] = chars[j-1]; + i += 1; + if cnt > 1: + for m in str(cnt): + chars[i] = m; + i += 1; + cnt = 1; + return i; + + + + diff --git "a/2018.11.29-leetcode443/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.11.29-leetcode443/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..dcc87c6d0 --- /dev/null +++ "b/2018.11.29-leetcode443/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,23 @@ +``` +class Solution { + public int compress(char[] chars) {//思路有一点,写的时候就缺胳膊少腿,又来模仿群主代码 + int count = 1; + int index = 0; + for (int i = 0; i < chars.length; i++) { + if (i + 1 == chars.length || chars[i] != chars[i+1]) { + chars[index++] = chars[i];//前后不同直接添加 + if (count > 1) { + String temp = String.valueOf(count);//转换成字符串,也可以变成字符数组,然后遍历。 + for(int k=0;k& chars) { + int n = chars.size(), char1 = 0; + for (int i = 0, j = 0; i < n; i = j) { + while (j < n && chars[j] == chars[i]) + ++j; + chars[char1++] = chars[i]; + if (j - i == 1) continue; + for (char c : to_string(j - i)) //个数 + chars[char1++] = c; + } + return char1; + } +}; diff --git "a/2018.11.29-leetcode443/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" "b/2018.11.29-leetcode443/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" new file mode 100644 index 000000000..f478a185b --- /dev/null +++ "b/2018.11.29-leetcode443/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" @@ -0,0 +1,37 @@ +#leetcode 443 +、、、 +class Solution { + public int compress(char[] chars) { + int count =1; + int index= 0; + for(int i=0;i1){ + //int转为String + String temp =String.valueOf(count); + + //将数量赋值到结果数组中 + for(int z=0;z1){ + char[] num = String.valueOf((i-index)).toCharArray(); + for (int j=0;j 1) { + char[] chs = String.valueOf(times).toCharArray(); + for (int j = 0; j < chs.length; j++) { + chars[index++] = chs[j]; + } + } + } + return index; +} diff --git "a/2018.11.29-leetcode443/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.11.29-leetcode443/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..8c057091f --- /dev/null +++ "b/2018.11.29-leetcode443/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,63 @@ +... +class Solution { +public: + int compress(vector& chars) { + int size = chars.size(); + int ret = 0; + + int num = 1; + int cur = 0; + while(cur+1 1) + { + stack s; + while(num != 0) + { + s.push(num%10+'0'); + num /= 10; + } + + while(!s.empty()) + { + chars[ret++] = s.top(); + s.pop(); + } + + } + num = 1; + } + + cur++; + } + + chars[ret++] = chars[cur]; + if(num > 1) + { + stack s; + while(num != 0) + { + s.push(num%10+'0'); + num /= 10; + } + + while(!s.empty()) + { + chars[ret++] = s.top(); + s.pop(); + } + + } + + + chars.resize(ret); + return ret; + } +}; +... diff --git a/2018.11.30-leetcode890/-.md b/2018.11.30-leetcode890/-.md new file mode 100644 index 000000000..ffa55dedd --- /dev/null +++ b/2018.11.30-leetcode890/-.md @@ -0,0 +1,28 @@ +class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + List result = new ArrayList<>(); + for (String str : words) { + if (str.length() != pattern.length()) { + continue; + } + Map map = new HashMap(); + for (int i = 0; i < str.length(); i++) { + Character c = map.get(str.charAt(i)); + if (c == null) { + if (map.containsValue(pattern.charAt(i))) { + break; + } + map.put(str.charAt(i), pattern.charAt(i)); + } else if (!c.equals(pattern.charAt(i))) { + break; + } + if (i == str.length() - 1) { + result.add(str); + } + } + // System.out.println(map); + + } + return result; + } +} diff --git a/2018.11.30-leetcode890/Avalon.md b/2018.11.30-leetcode890/Avalon.md new file mode 100644 index 000000000..7813ee0cc --- /dev/null +++ b/2018.11.30-leetcode890/Avalon.md @@ -0,0 +1,31 @@ +class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + List wlist = new ArrayList<>(); + int len = words.length; + String template = getTemplate(pattern); + for (int i=0;i cl = new ArrayList<>(); + String result=""; + int len = cs.length; + for (int i=0;i +如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后,我们就得到了所需的单词,那么单词与模式是匹配的。
+(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。)
+返回 words 中与给定模式匹配的单词列表。
+你可以按任何顺序返回答案。
+__提示__:
+1. 1 <= words.length <= 50
+2. 1 <= pattern.length = words[i].length <= 20
+### 1.2 输入与输出 +输入:
+* vector& words:给定的单词列表
+* string pattern:模式单词
+输出:
+* vector:与给定模式匹配的单词列表
+ +### 1.3 样例 +#### 1.3.1 样例1 +输入:
+words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
+ +输出:
+["mee","aqq"]
+ +解释:
+"mee" 与模式匹配,因为存在排列 {a -> m, b -> e, ...}。
+"ccc" 与模式不匹配,因为 {a -> c, b -> c, ...} 不是排列。 +因为 a 和 b 映射到同一个字母。
+## 2 思路描述与代码 +### 2.1 思路描述(双字典方法) +对每个属于单词列表words的单词word,使用dict1 记录 word 中的字符 word[i] 对 pattern 字符 pattern[i] 的映射
+使用dict2 记录 pattern 中的字符 pattern[i] 对 word 字符 word[i] 的映射
+```cpp +for(word in words){ + 初始化字典映射; + for(word[i] in word){ + if(word[i] 未被映射) + if(pattern[i] 未被映射) 双方记录映射关系; + else 确认 pattern[i] 映射的对象是不是 word[i],如果不是则失败; + if(word[i] 已被映射 且 映射对象不是 pattern[i]) 则失败; + } + 如果成功,记录word; +} +``` + +### 2.2 代码 +```cpp +vector findAndReplacePattern(vector& words, string pattern) { + vector ans; + for( auto word : words ){ + // dict1 记录 word 中的字符对 pattern 字符的映射 + // dict2 记录 pattern 中的字符对 word 字符的映射 + vector dict1(127, -1); + vector dict2(127, -1); + int word_len = word.size(); + int fail = 0; + for( int i = 0; i < word_len; i++ ){ + // 如果 word[i] 未被映射 + // (i) 如果 pattern[i] 未被映射,双方记录映射关系 + // (ii) 如果 pattern[i] 已被映射,确认 pattern[i] 映射的对象是不是 word[i],如果不是则失败 + if(dict1[word[i]] == -1){ + if(dict2[pattern[i]] == -1){ + dict1[word[i]] = pattern[i]; + dict2[pattern[i]] = word[i]; + } + else if(dict2[pattern[i]] != word[i]){ + fail = 1; + break ; + } + } + // 如果 word[i] 已被映射 且 映射对象不是 pattern[i],则失败 + else if(dict1[word[i]] != -1 && dict1[word[i]] != pattern[i]){ + fail = 1; + break ; + } + } + //如果成功,记录word + if(!fail) ans.push_back(word); + } + return ans; + } +``` +## 3 思考与拓展 +### 3.1 思考 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +双字典方法|O(1)|O(kn),k为word的长度,n为words的数目 +#### 3.1.3 难点分析 +1. 如何记录二者的映射关系; +2. 如何分辨映射存在一对多、多对一和多对多情况的出现。 + +### 3.1 扩展 +本题需要使用两个字典记录映射关系,不然可能导致一对多或者多对一情况。 + diff --git a/2018.11.30-leetcode890/GatesMa.md b/2018.11.30-leetcode890/GatesMa.md new file mode 100644 index 000000000..f9107c1cb --- /dev/null +++ b/2018.11.30-leetcode890/GatesMa.md @@ -0,0 +1,25 @@ +# C++ +``` +class Solution { +public: + bool strMatch(string str, string pattern){ + int len = str.length(); + for(int i=0;i < len;i++){ + for(int j=i+1;j < len;j++){ + if((str[i] == str[j]) && (pattern[i] != pattern[j])) return false; + if((str[i] != str[j]) && (pattern[i] == pattern[j])) return false; + } + } + return true; + } + vector findAndReplacePattern(vector& words, string pattern) { + vector set; + for(int i=0;i < words.size();i++){ + if(strMatch(words[i], pattern)){ + set.push_back(words[i]); + } + } + return set; + } +}; +``` diff --git a/2018.11.30-leetcode890/Istoryforever.md b/2018.11.30-leetcode890/Istoryforever.md new file mode 100644 index 000000000..4538e31e2 --- /dev/null +++ b/2018.11.30-leetcode890/Istoryforever.md @@ -0,0 +1,39 @@ +//Leetcode of 890 +class Solution { +public: + bool match(string str,string p){ + map m; + for(int i=0;i::iterator iter=m.find(str[i]); + if(iter==m.end()){ + m[str[i]]=p[i]; + continue; + }else{ + if(iter->second!=p[i]) + return false; + } + } + int seen[27]; + for(int i=0;i<27;i++)seen[i]=0; + for(map::iterator i=m.begin();i!=m.end();i++){ + if(!seen[i->second-'a']){ + seen[i->second-'a']=1; + }else{ + return false; + } + } + return true; + } + vector findAndReplacePattern(vector& words, string pattern) { + vector res; + for(vector::iterator i=words.begin();i!=words.end();i++){ + + if(match(*i,pattern)){ + res.push_back(*i); + } + + } + return res; + + } +}; diff --git a/2018.11.30-leetcode890/Ostrichcrab.md b/2018.11.30-leetcode890/Ostrichcrab.md new file mode 100644 index 000000000..077e78824 --- /dev/null +++ b/2018.11.30-leetcode890/Ostrichcrab.md @@ -0,0 +1,27 @@ +``` +class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + List ans = new ArrayList(); + for (String word: words) + if (match(word, pattern)) + ans.add(word); + return ans; + } + + public boolean match(String word, String pattern) { + Map m1 = new HashMap(); + Map m2 = new HashMap(); + + for (int i = 0; i < word.length(); ++i) { + char w = word.charAt(i); + char p = pattern.charAt(i); + if (!m1.containsKey(w)) m1.put(w, p); + if (!m2.containsKey(p)) m2.put(p, w); + if (m1.get(w) != p || m2.get(p) != w) + return false; + } + + return true; + } +} +``` diff --git a/2018.11.30-leetcode890/Sagittarius.md b/2018.11.30-leetcode890/Sagittarius.md new file mode 100644 index 000000000..f2839f033 --- /dev/null +++ b/2018.11.30-leetcode890/Sagittarius.md @@ -0,0 +1,35 @@ +``` +class Solution { +public: + vector findAndReplacePattern(vector& words, string pattern) { + vector s; + for(int i=0;i cmap; + string st=""; + bool flag=true; + if(words[i].size()!=pattern.size()) + continue; + for(int j=0,k=0;k findAndReplacePattern(vector& words, string pattern) { + vector s; + for(int i=0;i cmap; + string st=""; + bool flag=true; + if(words[i].size()!=pattern.size()) + continue; + for(int j=0,k=0;k findAndReplacePattern(String[] words, String pattern) { + List result = new ArrayList<>(); + boolean flag = false; + for (String word : words) { + if (word.length() != pattern.length()) { + continue; + } + flag = false; + char[] wordChars = word.toCharArray(); + char[] patternChars = pattern.toCharArray(); + //比较wordChars第i个位置与第j个位置的值,如果相同,那么patternChars第i个位置与第j个位置的值也要相同 + //如果wordChars第i个位置与第j个位置的值不同,那么patternChars第i个位置与第j个位置的值也要不同 + for (int i = 0; i < wordChars.length ; i++) { + for (int j = i + 1; j < wordChars.length; j++) { + if (wordChars[i] == wordChars[j]) { + if (patternChars[i] != patternChars[j]) { + flag = true; + break; + } + } + + if (wordChars[i] != wordChars[j]) { + if (patternChars[i] == patternChars[j]) { + flag = true; + break; + } + } + } + } + + if (!flag) { + result.add(word); + } + } + return result; + } + } + +``` diff --git a/2018.11.30-leetcode890/Sunny.md b/2018.11.30-leetcode890/Sunny.md new file mode 100644 index 000000000..c8588ba44 --- /dev/null +++ b/2018.11.30-leetcode890/Sunny.md @@ -0,0 +1,35 @@ +```java +class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + List result = new ArrayList<>(); + for (String word : words) { + int l = pattern.length(); + if (word.length() == l) { + boolean valid = true; + Map p = new HashMap<>(l); + for(int i=0; i findAndReplacePattern(String[] words, String pattern) { + List res = new ArrayList<>(); + for (String word : words) { + if (match(word, pattern)) { + res.add(word); + } + } + return res; + } + + private boolean match(String s, String p) { + int[] index1 = new int[26]; + int[] index2 = new int[26]; + for (int i = 0; i < s.length(); ++i) { + int i1 = s.charAt(i) - 'a'; + int i2 = p.charAt(i) - 'a'; + if (index1[i1] != index2[i2]) { + return false; + } + index1[i1] = index2[i2] = i + 1; + } + return true; + } +} +``` diff --git a/2018.11.30-leetcode890/Tony the Cyclist.md b/2018.11.30-leetcode890/Tony the Cyclist.md new file mode 100644 index 000000000..b4557bd3b --- /dev/null +++ b/2018.11.30-leetcode890/Tony the Cyclist.md @@ -0,0 +1,40 @@ +``` +import java.util.*; +class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + List result = new ArrayList(); + String p = transfor(pattern); + String w; + String ww; + for (int i = 0; i < words.length; i++){ + w = words[i]; + ww = transfor(w); + if (ww.equals(p)){ + result.add(w); + } + + } + return result; + } + + private String transfor(String s){ + Map m = new HashMap<>(); + char j = 0; + String ss = ""; + m.put(s.charAt(0), (char)(j + '0')); + for(int i = 1; i < s.length(); i++){ + if (s.charAt(i-1) != s.charAt(i)){ + if (m.containsKey(s.charAt(i))){ + ss += m.get(s.charAt(i)); + } + else { + ++j; + ss += (char)(j+'0'); + m.put(s.charAt(i), (char)(j + '0')); + } + } + } + return ss; + } +} +``` diff --git a/2018.11.30-leetcode890/kiritocly.md b/2018.11.30-leetcode890/kiritocly.md new file mode 100644 index 000000000..a1b915d21 --- /dev/null +++ b/2018.11.30-leetcode890/kiritocly.md @@ -0,0 +1,45 @@ + private static List solution(String[] words, String pattern) { + //定义一个list存放结果字符串 + List result = new ArrayList<>(); + char[] patternArray = pattern.toCharArray(); + //遍历字符串 + for (int i = 0; i < words.length; i++) { + //匹配字符串 + char[] wordArray = words[i].toCharArray(); + //是否匹配 + boolean flag = true; + //长度相同才能匹配 + if (wordArray.length == patternArray.length) { + //定义两个hashMap存放映射:words中的单词与pattern + Map hashMap1 = new HashMap<>(); + Map hashMap2 = new HashMap<>(); + //逐个字符匹配 + for (int j = 0; j < patternArray.length; j++) { + if (!hashMap1.containsKey(patternArray[j])) { + //如果不存在字符则向hashMap1存放映射关系对 + hashMap1.put(patternArray[j], wordArray[j]); + //判断hashMap2中是否存在反向映射关系对 + if (!hashMap2.containsKey(wordArray[j])) { + hashMap2.put(wordArray[j], patternArray[j]); + } else { + if (hashMap2.get(wordArray[j]) != patternArray[j]) { + //存在反向字符且当前判断的字符不相同 + flag = false; + break; + } + + } + } else { + if (hashMap1.get(patternArray[j]) != wordArray[j]) { + flag = false; + break; + } + } + } + } + if (flag) { + result.add(words[i]); + } + } + return result; + } diff --git a/2018.11.30-leetcode890/sourcema.md b/2018.11.30-leetcode890/sourcema.md new file mode 100644 index 000000000..aff17c534 --- /dev/null +++ b/2018.11.30-leetcode890/sourcema.md @@ -0,0 +1,34 @@ +# LeetCode 890 + class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + List list = new ArrayList<>(); + if (words.length == 0 || words == null) { + return list; + } + for (int i = 0; i < words.length; i++) { + String temp = words[i]; + if (match(temp, pattern)) { + list.add(temp); + } + } + return list; + } + private static boolean match(String temp, String pattern) { + Map map1 = new HashMap<>(); + Map map2 = new HashMap<>(); + for (int i = 0; i < temp.length(); i++) { + Character t = temp.charAt(i); + Character p = pattern.charAt(i); + if (!map1.containsKey(t)) { + map1.put(t, p); + } + if (!map2.containsKey(p)) { + map2.put(p, t); + } + if (map1.get(t) != p || map2.get(p) != t) { + return false; + } + } + return true; + } +} diff --git a/2018.11.30-leetcode890/suecurry.md b/2018.11.30-leetcode890/suecurry.md new file mode 100644 index 000000000..0336110fa --- /dev/null +++ b/2018.11.30-leetcode890/suecurry.md @@ -0,0 +1,54 @@ +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; + +public class leetcode890 { + public static List findAndReplacePattern(String[] words, String pattern){ + //定义一个ArrayList动态数组result,只不过里面存的值是String类型的 + List result = new ArrayList<>();//注意 new List();语法是错的 + char[] patternArray = pattern.toCharArray(); + //遍历String[]字符串数组words中的每个字符串 + for(int i=0; i judge = new HashMap<>();//HashMap 1 + HashMap judge2 = new HashMap<>();//HashMap 2 + for(int j=0; j findAndReplacePattern(String[] words, String pattern) { + List result=new LinkedList<>(); + int pHashCode=getHashCode(pattern); + for (String word : words) { + if (getHashCode(word)==pHashCode) { + result.add(word); + } + } + return result; + } + + public int getHashCode(String word){ + int[] arr=new int[26]; + int hashCode=0,i=1; + for (char c : word.toCharArray()) { + if (arr[c-'a']==0) { + arr[c-'a']=i++; + } + hashCode=hashCode*11+arr[c-'a']; + } + return hashCode; + } +} +``` diff --git a/2018.11.30-leetcode890/zjukk.md b/2018.11.30-leetcode890/zjukk.md new file mode 100644 index 000000000..9bb653294 --- /dev/null +++ b/2018.11.30-leetcode890/zjukk.md @@ -0,0 +1,32 @@ +C++: +class Solution { +public: + vector findAndReplacePattern(vector& words, string pattern) { + vector res; + for (int i = 0; i < words.size(); ++i) { + map mp; + map mp2; + string word = words[i]; + if (pattern.size() != word.size()) continue; + int j = 0; + for (; j < pattern.size(); ++j) { + if (mp.empty() || mp.count(pattern[j]) == 0) { + mp.insert({pattern[j], word[j]}); + } else if (mp[pattern[j]] != word[j]){ + break; + } + } + if (j != pattern.size()) continue; + int k = 0; + for (; k < pattern.size(); ++k) { + if (mp2.empty() || mp2.count(word[k]) == 0) { + mp2.insert({word[k],pattern[k]}); + } else if (mp2[word[k]] != pattern[k]) { + break; + } + } + if (k == pattern.size()) res.push_back(word); + } + return res; + } +}; diff --git "a/2018.11.30-leetcode890/\343\200\202V1ncentzzZ.md" "b/2018.11.30-leetcode890/\343\200\202V1ncentzzZ.md" new file mode 100644 index 000000000..f2c68a296 --- /dev/null +++ "b/2018.11.30-leetcode890/\343\200\202V1ncentzzZ.md" @@ -0,0 +1,57 @@ +题目描述: +你有一个单词列表 words 和一个模式 pattern,你想知道 words 中的哪些单词与模式匹配。 + +如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后,我们就得到了所需的单词,那么单词与模式是匹配的。 + +(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。) + +返回 words 中与给定模式匹配的单词列表。 + +你可以按任何顺序返回答案。 + + + +示例: + +输入:words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" +输出:["mee","aqq"] +解释: +"mee" 与模式匹配,因为存在排列 {a -> m, b -> e, ...}。 +"ccc" 与模式不匹配,因为 {a -> c, b -> c, ...} 不是排列。 +因为 a 和 b 映射到同一个字母。 + + +提示: + +1 <= words.length <= 50 +1 <= pattern.length = words[i].length <= 20 + + + +题解: TODO 8ms 待优化 +class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + + List result = new ArrayList<>(); + + char[] patternChar = pattern.toCharArray(); + String regex = ""; + for(int i=0; i findAndReplacePattern(String[] words, String pattern) { + List results = new ArrayList<>(); + Set characters = new HashSet(); + Map map = new HashMap<>();//map保存字符映射关系 + out: + for (int i = 0; i < words.length; i++) {//遍历words + for (int j = 0; j < pattern.length(); j++) {//初始化map + map.put(pattern.charAt(j), -288); + } + for (int k = 0; k < words[i].length(); k++) { + if (map.get(pattern.charAt(k)) == -288 && !characters.contains(words[i].charAt(k))) { + map.put(pattern.charAt(k), pattern.charAt(k) - words[i].charAt(k)); + characters.add(words[i].charAt(k)); + } else { + if (words[i].charAt(k) != -map.get(pattern.charAt(k)) + pattern.charAt(k)) { + characters.clear(); + continue out; + } + } + } + results.add(words[i]); + characters.clear(); + } + return results; + } diff --git "a/2018.11.30-leetcode890/\345\210\230\346\266\246\346\263\275.md" "b/2018.11.30-leetcode890/\345\210\230\346\266\246\346\263\275.md" new file mode 100644 index 000000000..a40421b2e --- /dev/null +++ "b/2018.11.30-leetcode890/\345\210\230\346\266\246\346\263\275.md" @@ -0,0 +1,84 @@ +## LeetCode890 +> language:Java + +> version:jdk1.7 + +```java +/** + * 思路一:把pattern弄成一个记忆,然后依次比较 + * 思路二:把pattern的某个特点记录下来,依次比较,然后再把下一个特点记录下来,依次比较... + * 下面代码是思路一的实现 + */ + public static List findAndReplacePattern(String[] words, String pattern) { + + List resultList = new ArrayList<>(); + List> patternRule = getRule(pattern); + + for (int i=0;i> wordRule = getRule(words[i]); + if (patternRule.size()!=wordRule.size()) continue; + for (int j=0;j patternRuleIntegers = patternRule.get(j); + List wordRuleIntegers = wordRule.get(j); + for (int m=0;m> getRule(String pattern){ + //记录pattern的所有特点 + List> characterList = new ArrayList<>(); + String currentCharacter = ""; + List recordList = new ArrayList<>(); + + for (int i=0;i tempList=new ArrayList<>(); + for (int j=i-1;;) { + tempIndex = pattern.indexOf(currentCharacter, j); + if (tempIndex==-1) break; + + recordList.add(tempIndex); + tempList.add(tempIndex); + if (tempIndex==pattern.length()-1) break; + j=tempIndex+1; + } + characterList.add(tempList); + } + return characterList; + } + + public static void main(String[] args) { + String[] words = new String[]{"abc","deq","meemccccm","aqqa","dkd","ccc"}; + List list = findAndReplacePattern(words, "abbacccca"); + for (String s : list){ + System.out.println(s); + } + } +``` diff --git "a/2018.11.30-leetcode890/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.11.30-leetcode890/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..3f09b1572 --- /dev/null +++ "b/2018.11.30-leetcode890/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,45 @@ +``` +class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + List list=new ArrayList<>(); + char [] pat=pattern.toCharArray(); + for(int i=0;i hash=new HashMap<>(); + HashMap hash2=new HashMap<>(); + for(int j=0;j m, b -> e, ...}。 +"ccc" 与模式不匹配,因为 {a -> c, b -> c, ...} 不是排列。 +因为 a 和 b 映射到同一个字母。 + + +提示: + +1 <= words.length <= 50 +1 <= pattern.length = words[i].length <= 20 + + */ +public class leetcode_890查找和替换模式 +{ + + public static void main(String[] args) + { + String[] wordsStrings= {"ddd","abc","deq","mee","aqq","dkd","ccc"}; + String pattern = "abb"; + System.out.println(findAndReplacePattern(wordsStrings, pattern)); + + } + + public static List findAndReplacePattern(String[] words, String pattern) + { + List list=new ArrayList(); + for(int i=0;i findAndReplacePattern(vector& words, string pattern) { + vectorres; + int n = pattern.size(); + for (string &word : words) { + if (word.size() != n)continue; + vectorpletter(256, '#'); + vectorwletter(256, '#'); + bool flag = false; + //进行映射 + for (int i = 0; i < n; i++) { + if (pletter[pattern[i]] == '#'&&wletter[word[i]]=='#') { + pletter[pattern[i]] = word[i]; + wletter[word[i]] = pattern[i]; + } + else if (pletter[pattern[i]] == word[i]&& wletter[word[i]]==pattern[i]) { + continue; + } + else { + flag = true; + break; + } + } + if (!flag)res.push_back(word); + } + return res; + } +}; diff --git "a/2018.11.30-leetcode890/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220" "b/2018.11.30-leetcode890/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220" new file mode 100644 index 000000000..2129c12f8 --- /dev/null +++ "b/2018.11.30-leetcode890/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220" @@ -0,0 +1,49 @@ +#leetcode 890 +``` +//思路是保证对应下标的权重是一样的,只需要比较权重就可以判断是否符合规则 +class Solution { + public static List findAndReplacePattern(String[] words, String pattern) { + List result = new ArrayList<>();//返回结果 + char [] patternArray = pattern.toCharArray();//字符串转字符数组 + for(int i=0;i judge = new HashMap<>();//hashmap1 + HashMap judge2 = new HashMap<>();//反向比较hashmap2 + for(int j=0;j 有一个words的列表和一个模式pattern,你想知道列表中哪个word和模式匹配。不考虑顺序,返回符合条件的word列表。 + +> word和模式匹配:如果存在一种字母间的双射,单词x→都转换为p(x) + +**例子** +>Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" +Output: ["mee","aqq"] + +>Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. +"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, +since a and b map to the same letter. + +**思想** + +(法1) +考虑将所有字母都映射为0123..这种形式 + +(法2) +既然提到双射,我们知道Python中zip(a,b)可以建立列表对应位置元素的元组。 + +利用长度的Trick。 + +**解法1** +映射为dic的长度,即按字母出现顺序映射为0,1,2... +```python +class Solution(object): + def findAndReplacePattern(self, words, pattern): + """ + :type words: List[str] + :type pattern: str + :rtype: List[str] + """ + return [word for word in words if self.helper(word) == self.helper(pattern)] + + def helper(self, word): + dic = {} + for c in word: + if c not in dic: + dic[c] = len(dic) + + return [dic[c] for c in word] +``` +用一个dict建立相互之间的映射。 +>注意双射的情况,即若键不存在,值也不能存在于dict.values()中。 +```python +class Solution(object): + def findAndReplacePattern(self, words, pattern): + """ + :type words: List[str] + :type pattern: str + :rtype: List[str] + """ + return [word for word in words if self.helper(word, pattern)] + + def helper(self, word, pattern): + dic = {} + for w, p in zip(word, pattern): + if w in dic: + if dic[w] != p: + return False + else: + if p in dic.values(): # 双射:abc - abb + return False + dic[w] = p + return True +``` + +**解法2** +Trick +```python +class Solution(object): + def findAndReplacePattern(self, words, pattern): + """ + :type words: List[str] + :type pattern: str + :rtype: List[str] + """ + return [word for word in words if len(word) == len(pattern) + and len(set(word)) == len(set(pattern)) == len(set(zip(word, pattern)))] +``` diff --git "a/2018.11.30-leetcode890/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.11.30-leetcode890/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..6d2cc909b --- /dev/null +++ "b/2018.11.30-leetcode890/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,40 @@ +class Solution { +public: + vector findAndReplacePattern(vector& words, string pattern) { + vector ret; + + int size = words.size(); + int n = pattern.length(); + + for(int i=0; i m; + map m1; + int j = 0; + for(j=0; j findAndReplacePattern(String[] words, String pattern) { + List list=new ArrayList<>(); + for(int i=0;i= 0; i--) { + if (map[chas1[i]] != map[chas2[i] + 256]) { + return false; + } + map[chas1[i]] = map[chas2[i] + 256] = i; + } + return true; + } +} +``` + diff --git a/2018.12.04-leetcode101/Avalon.md b/2018.12.04-leetcode101/Avalon.md new file mode 100644 index 000000000..3b7adc570 --- /dev/null +++ b/2018.12.04-leetcode101/Avalon.md @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if (root == null ){ + return true; + } + + return isSymmetric(root.left, root.right); + } + + public static boolean isSymmetric(TreeNode nodeA, TreeNode node_A){ + if (node_A == null && nodeA == null) { + return true; + } + if (node_A != null && nodeA != null) { + return node_A.val == nodeA.val && isSymmetric(nodeA.left, node_A.right) && isSymmetric(nodeA.right, node_A.left); + } + return false; + } +} diff --git a/2018.12.04-leetcode101/Be a fresh man.md b/2018.12.04-leetcode101/Be a fresh man.md new file mode 100644 index 000000000..897fc1d09 --- /dev/null +++ b/2018.12.04-leetcode101/Be a fresh man.md @@ -0,0 +1,103 @@ +## 101_(对称二叉树)Symmetric Tree +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定一个二叉树,检查它是否是镜像对称的。 +### 1.2 输入与输出 +输入: +* TreeNode* root:二叉树的根节点指针 + +输出: +* bool:是否是对称二叉树 + +### 1.3 样例 +#### 1.3.1 样例1 +输入: 给定二叉树: [1,2,2,3,4,4,3] , + + 1 + / \ + 2 2 + / \ / \ + 3 4 4 3 +输出: true + +#### 1.3.2 样例2 +输入:给定二叉树: [1,2,2,null,3,null,3] , + + 1 + / \ + 2 2 + \ \ + 3 3 +输出: false
+## 2 思路描述与代码 +### 2.1 思路描述(队列法) +利用队列做判断 +```cpp +根节点左右孩子入队; +while( 队列非空 ){ + 取出队列两个元素 tmp1, tmp2; + //如果当前节点都是空节点,结束本次循环,即不需要检查后续节点 + if(tmp1 == null && tmp2 == null) continue; + //如果不对称,则返回false + if((tmp1 == nullptr && tmp2) || (tmp2 == nullptr && tmp1) || (tmp1->val != tmp2->val)) + return false; + //剩下的可能情况就是左右非空且当前节点的值相等,即对称 + //然后对这两个节点的左右孩子节点对称入队,保持对称性 + //对称入队 + tmp1 左孩子入队; + tmp2 右孩子入队; + tmp1 右孩子入队; + tmp2 左孩子入队; +} +return true; +``` + +### 2.2 代码 +```cpp +bool isSymmetric(TreeNode* root) { + if(root == nullptr) + return true; + //使用队列做遍历,这是也可以使用堆栈 + queue q; + //根节点就不用判断了,直接加入左右孩子节点 + q.push(root->left); + q.push(root->right); + while( !q.empty() ){ + //从队列弹出两个节点 + TreeNode* tmp1 = q.front(); + q.pop(); + TreeNode* tmp2 = q.front(); + q.pop(); + //如果都是根节点,则结束本次循环 + if(tmp1 == nullptr && tmp2 == nullptr) + continue; + //如果不对称,则返回false + if((tmp1 == nullptr && tmp2) || (tmp2 == nullptr && tmp1) || (tmp1->val != tmp2->val)) + return false; + //对称入队 + q.push(tmp1->left); + q.push(tmp2->right); + q.push(tmp1->right); + q.push(tmp2->left); + } + //都是对称的,返回真 + return true; +} + +``` +## 3 思考与拓展 +### 3.1 思考 +本题,利用队列和堆栈做遍历都可以解决这个问题。 +#### 3.1.1 其他方法 +#### 3.1.1.1 递归法 +一棵对称的二叉树必然是左右孩子相等且左右孩子也都是一棵对称的二叉树,利用该思路做递归就行了,这里就不继续写代码了。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +队列法|O(2^h),h是树的高度|O(n) +递归法|O(n)|O(n) +#### 3.1.3 难点分析 +1. 对称与非对称的判断 + +### 3.2 拓展 +如果让你判断是不是同构的呢? diff --git a/2018.12.04-leetcode101/Despacito.md b/2018.12.04-leetcode101/Despacito.md new file mode 100644 index 000000000..e1e85f4fa --- /dev/null +++ b/2018.12.04-leetcode101/Despacito.md @@ -0,0 +1,52 @@ +# leetcode 101 Symmetric Tree +## 1. Description +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. + +## 2. Solution +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def isSymmetric(self, root): + """ + :type root: TreeNode + :rtype: bool + """ + if root == None: + return True + return self.comroot(root.left, root.right) + + def comroot(self, left, right): + if left == None and right == None: + return True + elif left == None or right == None: + return False + elif left.val != right.val: + return False + return self.comroot(left.left, right.right) and self.comroot(left.right, right.left) +``` \ No newline at end of file diff --git a/2018.12.04-leetcode101/Istoryforever.md b/2018.12.04-leetcode101/Istoryforever.md new file mode 100644 index 000000000..97d6054b4 --- /dev/null +++ b/2018.12.04-leetcode101/Istoryforever.md @@ -0,0 +1,25 @@ +leetcode of 101 +``` +/** + * 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: + bool isSymmetric(TreeNode* p1,TreeNode * p2){ + if((p1 == nullptr && p2!=nullptr) || (p2 == nullptr && p1!=nullptr)) return false; + if(p1 == nullptr && p2 == nullptr) return true; + if(p1->val != p2->val) return false; + return isSymmetric(p1->left,p2->right) && isSymmetric(p1->right,p2->left); + + } + bool isSymmetric(TreeNode* root) { + return isSymmetric(root,root); + } +}; +``` diff --git a/2018.12.04-leetcode101/MQQM.cpp b/2018.12.04-leetcode101/MQQM.cpp new file mode 100644 index 000000000..4ddbc6cff --- /dev/null +++ b/2018.12.04-leetcode101/MQQM.cpp @@ -0,0 +1,43 @@ +/* + 题目: + 给定一个二叉树,检查它是否是镜像对称的。 + + 做法: + 给定对应位置上的两个节点,递归判断这两个节点是否一致。 + + 参考: + https://www.cnblogs.com/xiaozhuyang/p/7376749.html +*/ + +/** + * 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: + bool isSymmetric(TreeNode* root) { + if( root == NULL ){ + return true; + } + + return isEqual(root->left, root->right); + } + bool isEqual(TreeNode* left, TreeNode* right){//给定的两个节点已经是对应位置上的节点 + if( left == NULL && right == NULL ){//两个节点都是空 + return true; + } + if( left == NULL || right == NULL ){//有一个节点是空 + return false; + } + if( left->val != right->val ){//两个节点都存在,但是不相同 + return false; + } + + return isEqual(left->left, right->right) && isEqual(left->right, right->left); + } +}; diff --git a/2018.12.04-leetcode101/Saul.md b/2018.12.04-leetcode101/Saul.md new file mode 100644 index 000000000..1fff77b94 --- /dev/null +++ b/2018.12.04-leetcode101/Saul.md @@ -0,0 +1,24 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + return isMirror(root, root); +} + +public boolean isMirror(TreeNode t1, TreeNode t2) { + if (t1 == null && t2 == null) return true; + if (t1 == null || t2 == null) return false; + return (t1.val == t2.val) + && isMirror(t1.right, t2.left) + && isMirror(t1.left, t2.right); +} +} +``` diff --git a/2018.12.04-leetcode101/Tony the Cyclist.md b/2018.12.04-leetcode101/Tony the Cyclist.md new file mode 100644 index 000000000..a1e44e5c1 --- /dev/null +++ b/2018.12.04-leetcode101/Tony the Cyclist.md @@ -0,0 +1,83 @@ +递归 +```java +class Solution { + public boolean isSymmetric(TreeNode root) { + if (root == null){ + return true; + } + else { + if (check(root.left, root.right)){ + return true; + } + else { + return false; + } + } + } + + public static boolean check(TreeNode node1, TreeNode node2){ + if (node1 == null && node2 == null){ + return true; + } + else if (node1 == null || node2 == null){ + return false; + } + return node1.val == node2.val && check(node1.right, node2.left) && check(node1.left, node2.right); + } +} +``` +非递归 +```java +import java.util.*; +class Solution { + public boolean isSymmetric(TreeNode root) { + if ((root == null) || (root.left == null && root.right == null)){ + return true; + } + else if (root.left == null || root.right == null){ + return false; + } + else { + ArrayDeque d = new ArrayDeque(); + d.addFirst(root.left); + d.addLast(root.right); + while (d.size() != 0){ + TreeNode leftnode = d.pollFirst(); + TreeNode rightnode = d.pollLast(); + if (leftnode == null && rightnode == null){ + return true; + } + else if (leftnode == null || rightnode == null){ + return false; + } + else if (leftnode.val != rightnode.val){ + return false; + } + else { + if (rightnode.right != null && leftnode.left != null){ + d.addLast(rightnode.right); + d.addFirst(leftnode.left); + } + else if (rightnode.right == null && leftnode.left == null){ + + } + else { + return false; + } + if (rightnode.left != null && leftnode.right != null){ + d.addFirst(rightnode.left); + d.addLast(leftnode.right); + } + else if (rightnode.left == null && leftnode.right == null){ + + } + else { + return false; + } + } + } + return true; + } + } +} +``` diff --git a/2018.12.04-leetcode101/WhiteNight.md b/2018.12.04-leetcode101/WhiteNight.md new file mode 100644 index 000000000..5b769916c --- /dev/null +++ b/2018.12.04-leetcode101/WhiteNight.md @@ -0,0 +1,58 @@ +>```java +>/** +> *给定一个二叉树,检查它是否是镜像对称的。 +> * +> */ +>public class Tree9 +>{ +> public static class TreeNode +> { +> int data; +> TreeNode left; +> TreeNode right; +> +> TreeNode(int val) { +> data = val; +> } +> } +> +> public boolean isSymmetric(TreeNode root) +> { +> if (root == null) +> return true; +> return checkIsSymmetric(root.left, root.right); +> } +> +> public static boolean checkIsSymmetric(TreeNode leftNode, TreeNode rightNode) +> { +> if (leftNode == null && rightNode == null) +> return true; +> if ((leftNode == null && rightNode != null) || (leftNode != null && rightNode == null)) +> return false; +> if (leftNode.data != rightNode.data) +> return false; +> return checkIsSymmetric(leftNode.left, rightNode.right) && checkIsSymmetric(leftNode.right, rightNode.left); +> } +> +> public static void main(String[] args) +> { +> TreeNode p = new TreeNode(1); +> p.left = new TreeNode(2); +> p.right = new TreeNode(2); +> p.left.left = new TreeNode(3); +> p.right.right = new TreeNode(3); +> +> TreeNode q = new TreeNode(1); +> q.left = new TreeNode(2); +> q.right = new TreeNode(2); +> q.left.right = new TreeNode(3); +> q.right.right = new TreeNode(3); +> +> Tree9 t = new Tree9(); +> System.out.println(t.isSymmetric(p)); +> System.out.println(t.isSymmetric(q)); +> +> } +> +>} +>``` \ No newline at end of file diff --git a/2018.12.04-leetcode101/fish.md b/2018.12.04-leetcode101/fish.md new file mode 100644 index 000000000..609c8569e --- /dev/null +++ b/2018.12.04-leetcode101/fish.md @@ -0,0 +1,58 @@ +``` +class Solution { + public boolean isSymmetric(TreeNode treeNode) { + if (treeNode == null) { + return true; + }else { + return isSymmetric(treeNode.getLeft(), treeNode.getRight()); + } + } + + public boolean isSymmetric(TreeNode left, TreeNode right) { + if (left == null && right == null) { + return true; + } + if (left == null || right == null) { + return false; + } + if (left.getVal() != right.getVal()) { + return false; + } + return isSymmetric(left.getLeft(), right.getRight()) && isSymmetric(left.getRight(), right.getLeft()); + } +} +class TreeNode{ + private int val; + private TreeNode left; + private TreeNode right; + + public TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } + + public int getVal() { + return val; + } + + public void setVal(int val) { + this.val = val; + } + + public TreeNode getLeft() { + return left; + } + + public void setLeft(TreeNode left) { + this.left = left; + } + + public TreeNode getRight() { + return right; + } + + public void setRight(TreeNode right) { + this.right = right; + } +} \ No newline at end of file diff --git a/2018.12.04-leetcode101/kiritocly.md b/2018.12.04-leetcode101/kiritocly.md new file mode 100644 index 000000000..51cd1718d --- /dev/null +++ b/2018.12.04-leetcode101/kiritocly.md @@ -0,0 +1,33 @@ + private static boolean solution(TreeNode root) { + if (root == null) { + return true; + } else { + //二叉树对称的条件 + //(1)左子树和右子树对称 + //(2)左子树的左子树和右子树的右子树对称 + //(3)左子树的右子树和右子树的左子树对称 + //递归判断 + return judge(root.leftNode, root.rightNode); + } + + } + + private static boolean judge(TreeNode leftNode, TreeNode rightNode) { + if (leftNode == null && rightNode == null) { + return true; + } else if (leftNode == null || rightNode == null) { + return false; + } + //条件(1) + if (leftNode.value != rightNode.value) { + return false; + } + //条件(2) + boolean flag1 = judge(leftNode.leftNode, rightNode.rightNode); + //条件(3) + boolean flag2 = judge(leftNode.rightNode, rightNode.leftNode); + if (flag1 && flag2) { + return true; + } + return false; + } diff --git a/2018.12.04-leetcode101/marguerite.md b/2018.12.04-leetcode101/marguerite.md new file mode 100644 index 000000000..171a682df --- /dev/null +++ b/2018.12.04-leetcode101/marguerite.md @@ -0,0 +1,96 @@ +101_(对称二叉树)Symmetric Tree +给定一个二叉树,检查它是否是镜像对称的。 + +输入: +TreeNode* root:二叉树的根节点指针 +输出: +bool:是否是对称二叉树 + +输入: 给定二叉树: [1,2,2,3,4,4,3] , + 1 + / \ + 2 2 + / \ / \ +3 4 4 3 +输出: true + +solution1 + +判断是否是镜像对称,重要的就是判断对应位置的2个结点的值是否相等。用双端队列来实现 + +public boolean isSymmetric(TreeNode root){ + if(root == null){ + return true; + } + //队列做遍历 + Deque deque = new LinkedList(); + //根节点不用判断,直接加入左右孩子结点 + deque.addFirst(root.left); + deque.addLast(root.right); + + TreeNode preNode = null; + TreeNode postNode = null; + + while(!deque.isEmpty()){ + //取出列队两个元素 + preNode = deque.pollFirst(); + postNode = deque.pollLast(); + //如果当前结点是空结点,结束本次循环,即不需要检查后续结点 + if(preNode == null && postNode == null){ + continue; + } + //如果不对称返回false, + if(preNode == null || postNode == null){ + return false; + } + if(preNode.val != postNode.val){ + return false; + } else{ + deque.addFirst(preNode.right);//preNode右孩子入队 + deque.addFirst(preNode.left);//preNode左孩子入队 + + deque.addLast(postNode.left);//postNode左孩子入队 + deque.addLast(postNode.right);//postNode右孩子入队 + } + } + return true;//都是对称的返回真 + } + + +solution2 + public boolean isSysmmetric2(TreeNode root){ + if(root == null){ + return true; + } + return checkNodes(root.left,root.right); + } + + public boolean checkNodes(TreeNode node1,TreeNode node2){ + if(node1 == null && node2 == null){ + return true; + } + if(node1 == null || node2 == null){ + return false; + } + if(node1.val != node2.val){ + return false; + } else{ + return checkNodes(node1.left,node2.right) && checkNodes(node1.right,node2.left); + } + } + + + + + + + + + + + + + + + + diff --git a/2018.12.04-leetcode101/sourcema.md b/2018.12.04-leetcode101/sourcema.md new file mode 100644 index 000000000..bc477d192 --- /dev/null +++ b/2018.12.04-leetcode101/sourcema.md @@ -0,0 +1,27 @@ +# LeetCode 101 + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + class Solution { + public boolean isSymmetric(TreeNode root) { + if (root == null) { + return true; + } + return symmetric(root.left, root.right); + } + private boolean symmetric(TreeNode p, TreeNode q) { + if (p == null && q == null) { + return true; + } + if ((p == null && q != null) || (p != null && q == null) || p.val != q.val) { + return false; + } + return symmetric(p.left, q.right) && symmetric(p.right, q.left); + } + } diff --git a/2018.12.04-leetcode101/syuan.md b/2018.12.04-leetcode101/syuan.md new file mode 100644 index 000000000..9048177da --- /dev/null +++ b/2018.12.04-leetcode101/syuan.md @@ -0,0 +1,65 @@ +##### 题目 + +``` +给定一个二叉树,检查它是否是镜像对称的。 + +例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 + + 1 + / \ + 2 2 + / \ / \ +3 4 4 3 + +但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: + + 1 + / \ + 2 2 + \ \ + 3 3 +``` +##### 代码 +递归 +``` +public boolean isSymmetric(TreeNode root) { + if (root==null) { + return true; + }else{ + return isSymmetric(root.left,root.right); + } + } + + public boolean isSymmetricCore(TreeNode leftNode, TreeNode rightNode){ + if (leftNode==null && rightNode==null) { + return true; + } + if (leftNode.val!=rightNode.val || leftNode==null || rightNode==null) { + return false; + } + return isSymmetricCore(leftNode.left,rightNode.right) && isSymmetricCore(leftNode.right,rightNode.left); + } +``` +##### 非递归法 + +``` +class Solution { + public boolean isSymmetric(TreeNode root) { + if(root == null) return true; + Stack stack = new Stack(); + stack.push(root.left); + stack.push(root.right); + while(!stack.empty()) { + TreeNode right = stack.pop(); + TreeNode left = stack.pop(); + if (left == null && right == null) continue; + else if (left == null || right == null || right.val != left.val) return false; + stack.push(left.left); + stack.push(right.right); + stack.push(left.right); + stack.push(right.left); + } + return true; + } +} +``` diff --git "a/2018.12.04-leetcode101/\343\200\202V1ncentzzZ.md" "b/2018.12.04-leetcode101/\343\200\202V1ncentzzZ.md" new file mode 100644 index 000000000..191025761 --- /dev/null +++ "b/2018.12.04-leetcode101/\343\200\202V1ncentzzZ.md" @@ -0,0 +1,43 @@ +101. 对称二叉树 + +给定一个二叉树,检查它是否是镜像对称的。 + +例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 + + 1 + / \ + 2 2 + / \ / \ +3 4 4 3 +但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: + + 1 + / \ + 2 2 + \ \ + 3 3 + +``` + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if(root == null) return true; + return symmetricCheck(root.left,root.right); + } + + public boolean symmetricCheck(TreeNode node1,TreeNode node2){ + if(node1 == null && node2 == null) return true; + if(node1 == null || node2 == null) return false; + return (node1.val != node2.val) ? false : symmetricCheck(node1.left,node2.right) && symmetricCheck(node1.right,node2.left); + + } +} +``` diff --git "a/2018.12.04-leetcode101/\343\200\202\343\200\202\343\200\202.md" "b/2018.12.04-leetcode101/\343\200\202\343\200\202\343\200\202.md" new file mode 100644 index 000000000..f344327ea --- /dev/null +++ "b/2018.12.04-leetcode101/\343\200\202\343\200\202\343\200\202.md" @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if(root == null)return true; + return isSymmetric2(root.left,root.right); + } + + private boolean isSymmetric2(TreeNode left, TreeNode right) { + if (left != null && right != null && left.val == right.val){ + return isSymmetric2(left.left,right.right) && isSymmetric2(left.right,right.left); + } + return (left==null && right == null); + } +} diff --git "a/2018.12.04-leetcode101/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.04-leetcode101/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..87c2b14f3 --- /dev/null +++ "b/2018.12.04-leetcode101/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,22 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + return cal(root,root); + } + + boolean cal(TreeNode r1,TreeNode r2){ + if(r1==null&&r2==null)return true; + if(r1==null||r2==null)return false; + return r1.val==r2.val&&cal(r1.left,r2.right)&&cal(r1.right,r2.left); + } +} +``` diff --git "a/2018.12.04-leetcode101/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.12.04-leetcode101/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..0ac1a8b14 --- /dev/null +++ "b/2018.12.04-leetcode101/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,34 @@ +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution {//递归方式 + public boolean isSymmetric(TreeNode root) { + if(root==null){ + return true; + + } + return isSymmetric(root.left,root.right); + + } + public boolean isSymmetric(TreeNode left,TreeNode right){ + if(left==null&&right==null){//无左右子树,则节点本身是对称的 + return true; + }else if(left==null||right==null){//只含有一个左子树或者右子树,不对称 + return false; + } + if(left.val!=right.val){ + return false; + } + + + return isSymmetric(left.right,right.left)&&isSymmetric(left.left,right.right);//左子树的右子树和右子树的左子树是否对称。 + } +} +``` diff --git "a/2018.12.04-leetcode101/\345\246\256\345\217\257.md" "b/2018.12.04-leetcode101/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..6a0c165bb --- /dev/null +++ "b/2018.12.04-leetcode101/\345\246\256\345\217\257.md" @@ -0,0 +1,88 @@ +```java +package sy181204; + +/** + * @author suyuan + * +给定一个二叉树,检查它是否是镜像对称的。 + +例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 + + 1 + / \ + 2 2 + / \ / \ +3 4 4 3 +但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: + + 1 + / \ + 2 2 + \ \ + 3 3 +说明: + +如果你可以运用递归和迭代两种方法解决这个问题,会很加分。 + */ +public class leetcode_101对称二叉树 +{ + + public static void main(String[] args) + { + TreeNode node1=new TreeNode(1); + TreeNode node2=new TreeNode(2); + TreeNode node3=new TreeNode(2); + TreeNode node4=new TreeNode(3); + TreeNode node5=new TreeNode(3); + TreeNode node6=new TreeNode(4); + TreeNode node7=new TreeNode(4); + node1.left=node2; + node1.right=node3; + + node2.left=node4; + node2.right=node6; + + node3.left=node7; + node3.right=node5; + + node4.left=null; + node4.right=null; + node5.left=null; + node5.right=null; + node6.left=null; + node6.right=null; + node7.left=null; + node7.right=null; + + System.out.println(isSymmetric(node1)); + + } + + public static boolean isSymmetric(TreeNode root) + { + if(root==null) + return true; + return isSy(root.left, root.right); + } + + public static boolean isSy(TreeNode left,TreeNode right) + { + if(left==null && right==null) + return true; + if((left==null && right!=null) || (right==null && left!=null)) + return false; + if(left.val!=right.val) + return false; + return isSy(left.left, right.right) && isSy(left.right, right.left); + } + +} + + class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } + +``` diff --git "a/2018.12.04-leetcode101/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.04-leetcode101/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..9ed6e6c06 --- /dev/null +++ "b/2018.12.04-leetcode101/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,82 @@ +### [101. Symmetric Tree](https://leetcode.com/problems/symmetric-tree/description/) +**题目描述** +> 判断是否是镜像二叉树(对称) + +**例子** +略 + +**思想** +(递归) +定义一辅助函数,输入为left和right,判断是否相等。 +(迭代) +定义两个栈,层次遍历时判断,并分别从左向右和从右向左存储。 + +**解法1** +递归 +```python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def isSymmetric(self, root): + """ + :type root: TreeNode + :rtype: bool + """ + if not root: + return True + return self.helper(root.left, root.right) + + def helper(self, left, right): + if not left and not right: + return True + if not left or not right or left.val != right.val: + return False + return self.helper(left.left, right.right) and self.helper(left.right, right.left) +``` +**解法2** +迭代 +```python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def isSymmetric(self, root): + """ + :type root: TreeNode + :rtype: bool + """ + if not root or not root.left and not root.right: + return True + if not root.left or not root.right: + return False + + queue1, queue2 = [root.left], [root.right] + while queue1 and queue2: + node1 = queue1.pop(0) + node2 = queue2.pop(0) + + if node1.val != node2.val: + return False + + if node1.left and node2.right: + queue1.append(node1.left) + queue2.append(node2.right) + elif node1.left or node2.right: + return False + + if node1.right and node2.left: + queue1.append(node1.right) + queue2.append(node2.left) + elif node1.right or node2.left: + return False + return True +``` \ No newline at end of file diff --git "a/2018.12.04-leetcode101/\346\235\250.md" "b/2018.12.04-leetcode101/\346\235\250.md" new file mode 100644 index 000000000..6afe9301b --- /dev/null +++ "b/2018.12.04-leetcode101/\346\235\250.md" @@ -0,0 +1,25 @@ +``` + /** + * 如果一个树的左子树与右子树镜像对称,那么这个树是对称的。 + * 如果同时满足下面的条件,两个树互为镜像: + * 1.它们的两个根结点具有相同的值。 + * 2.每个树的右子树都与另一个树的左子树镜像对称。 + */ + public boolean isSymmetric(TreeNode root) { + if(root == null ){ + return true; + } + return isMirrorSymmetry(root.left,root.right); + } + + public boolean isMirrorSymmetry(TreeNode left,TreeNode right){ + if(left==null && right==null){ + return true; + } + if(left==null || right==null){ + return false; + } + return left.val==right.val && isMirrorSymmetry(left.left,right.right) && isMirrorSymmetry(left.right,right.left); + } + +``` diff --git "a/2018.12.04-leetcode101/\346\271\233\346\261\237\347\224\262\351\270\237.md" "b/2018.12.04-leetcode101/\346\271\233\346\261\237\347\224\262\351\270\237.md" new file mode 100644 index 000000000..65dcb627d --- /dev/null +++ "b/2018.12.04-leetcode101/\346\271\233\346\261\237\347\224\262\351\270\237.md" @@ -0,0 +1,45 @@ +#### 递归 +``` +public boolean isSymmetric(TreeNode root) { + if (root == null) + return true; + return dfs(root.left, root.right); +} + +private boolean dfs(TreeNode node1, TreeNode node2) { + if ((node1 == null && node2 == null)) { + return true; + } else if (node1 != null && node2 != null) { + if (node1.val != node2.val) { + return false; + } + } else { + return false; + } + return dfs(node1.left, node2.right) && dfs(node1.right, node2.left); +} +``` + +#### 非递归 +``` +public boolean isSymmetric(TreeNode root) { + Queue q = new LinkedList<>(); + q.add(root); + q.add(root); + while (!q.isEmpty()) { + TreeNode t1 = q.poll(); + TreeNode t2 = q.poll(); + if (t1 == null && t2 == null) { + continue; + } + if (t1 == null || t2 == null || t1.val != t2.val) { + return false; + } + q.add(t1.left); + q.add(t2.right); + q.add(t1.right); + q.add(t2.left); + } + return true; +} +``` diff --git "a/2018.12.04-leetcode101/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.04-leetcode101/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..df8f5dbf9 --- /dev/null +++ "b/2018.12.04-leetcode101/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,49 @@ +``` +/** + * 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: + bool isSymmetric(TreeNode* root) { + if(!root) return true; + + queue q1; + queue q2; + q1.push(root->left); + q2.push(root->right); + + + while(!q1.empty() && !q2.empty()) + { + TreeNode *l = q1.front(); + TreeNode *r = q2.front(); + + q1.pop(); + q2.pop(); + + if( (!l&&r) || (l&&!r) ) return false; + + if(l && r) + { + if(l->val != r->val) + return false; + + q1.push(l->left); + q1.push(l->right); + + q2.push(r->right); + q2.push(r->left); + } + + } + + return true; + } +}; +``` diff --git "a/2018.12.04-leetcode101/\351\223\201\347\224\267\347\245\236sama.md" "b/2018.12.04-leetcode101/\351\223\201\347\224\267\347\245\236sama.md" new file mode 100644 index 000000000..df7ffe32a --- /dev/null +++ "b/2018.12.04-leetcode101/\351\223\201\347\224\267\347\245\236sama.md" @@ -0,0 +1,68 @@ + + + + +## 101.对称二叉树 + +>[https://leetcode-cn.com/problems/symmetric-tree/](https://leetcode-cn.com/problems/symmetric-tree/) + +### 一、题目 + +给定一个二叉树,检查它是否是镜像对称的。 + +例如,二叉树 `[1,2,2,3,4,4,3]` 是对称的。 + +``` + 1 + / \ + 2 2 + / \ / \ + 3 4 4 3 +``` + +但是下面这个 `[1,2,2,null,3,null,3]` 则不是镜像对称的: + +``` + 1 + / \ + 2 2 + \ \ + 3 3 +``` + +### 二、思路 + +- 二叉树问题锁定递归 + +- 如何判定一棵树是否镜像:整棵树镜像=左子树镜像&&右子树镜像 + - [ ] 条件一:左孩子为空&&右孩子为空(没有孩子的情况) + - [ ] 条件二:左孩子值==右孩子值(有两个孩子的情况);(只有一个孩子的肯定不能互为镜像) + - [ ] 条件三:左左值==右右值&&左右值==右左值 + +- 出口:root==null 返回true + +### 三、题解 + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { int val; TreeNode + * left; TreeNode right; TreeNode(int x) { val = x; } } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if (root == null)return true;//出口条件 + return isMirror(root.left, root.right); + } + + public boolean isMirror(TreeNode left,TreeNode right){ + if(left==null&&right==null)return true; + if(left==null||right==null)return false; + if(left.val!=right.val)return false; + return isMirror(left.left,right.right)&&isMirror(left.right,right.left); + } +} +``` + + + diff --git "a/2018.12.04-leetcode101/\351\230\263.md" "b/2018.12.04-leetcode101/\351\230\263.md" new file mode 100644 index 000000000..819d77ef9 --- /dev/null +++ "b/2018.12.04-leetcode101/\351\230\263.md" @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if(root == null) { + return true;//根节点为空,返回true + }else { + return isSymmetric(root.left, root.right); + } + } + public boolean isSymmetric(TreeNode pleft, TreeNode pright) { + if(pleft == null && pright == null) { + return true;//说明只有一个根节点,返回true + } + if(pleft == null || pright == null) { + return false;//一个子树为空,另一个子树不为空,返回false + } + //都不为空的情况下判断是否相等 + if(pleft.val != pright.val) { + return false; + } + //继续判断左子树与右子树是否对称相等 + return isSymmetric(pleft.left, pright.right)&&isSymmetric(pleft.right, pright.left); + } +} diff --git a/2018.12.05-leetcode102/-.md b/2018.12.05-leetcode102/-.md new file mode 100644 index 000000000..65b48bfbe --- /dev/null +++ b/2018.12.05-leetcode102/-.md @@ -0,0 +1,34 @@ +public class Solution_102 { + public List> levelOrder(TreeNode root) { + List> result = new ArrayList<>(); + + List list = new ArrayList<>(); + if(root==null) + return result; + list.add(root); + while (list.size() != 0) { + List temp = new ArrayList<>(); + List list2 = new ArrayList<>(); + for (TreeNode node : list) { + temp.add(node.val); + if(node.left!=null) + list2.add(node.left); + if (node.right!=null) + list2.add(node.right); + } + result.add(temp); + list=list2; + } + + return result; + } +} +class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/2018.12.05-leetcode102/Avalon.md b/2018.12.05-leetcode102/Avalon.md new file mode 100644 index 000000000..4279df10a --- /dev/null +++ b/2018.12.05-leetcode102/Avalon.md @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrder(TreeNode root) { + List> list = new ArrayList>(); + //List templist=new ArrayList();//这个list 没有实现对应接口 + LinkedList llist = new LinkedList();//但是这个 linkedlist 实现了 deque 接口 + //LinkedList templist = new LinkedList();//临时队列-用于存放同一排 + if (root == null)return list; + llist.add(root); + TreeNode current; + while (!llist.isEmpty() ) { + List templist = new ArrayList(); + int templen = llist.size(); + for (int i=0;i +### 1.2 输入与输出 +输入:
+* TreeNode* root:二叉树的根节点指针
+输出:
+* vector>:层次遍历的结果,是一个二维矢量的形式 +### 1.3 样例 +#### 1.3.1 样例1 +输入: 给定二叉树: [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 + +输出: + + [ + [3], + [9,20], + [15,7] + ] + +## 2 思路描述与代码 +### 2.1 思路描述(基于队列的二叉树层次遍历) +二叉树的层次遍历可以利用队列来做,其思路也很简单。
+这里为了把每层的结果记录下来,对BFS的代码结构稍微改动了下,即里面用了个 for 循环做当前层遍历。
+```cpp +初始化二叉树层次遍历的二维矢量 res ; +头结点入队; +while( 队列不空 ){ + 初始化当前层的遍历结果 level; + 获取当前层的数目数 len; + for( int i = 0; i < len; i++ ){ + 取出当前层的节点tmp并保存至 level; + 左右孩子非空则入队; + } + 将 level 保存至 res ; +} +返回 res ; +``` +比如给定二叉树: [3,9,20,null,null,15,7];
+首先根节点3入队,然后进入 while 循环;
+此时队列不空,有1个元素3,for 循环后有 res = {[3]}, 队列里面有元素[9, 20];
+此时队列不空,有元素[9, 20],for 循环后有 res = {[3],[9,20]}, 队列里面有元素[15, 7];
+此时队列不空,有元素[15, 7],for 循环后有 res = {[3],[9,20], [15,7]}, 队列里面没有元素;
+此时队列空后,返回 res = {[3],[9,20], [15,7]} 。 + +### 2.2 代码 +```cpp +vector> levelOrder(TreeNode* root) { + vector> res; + //如果输入为空 + if (root == NULL) { + return res; + } + //队列做BFS + queue q; + q.push(root); + while( !q.empty() ){ + //获取当前层的数目 + int len = q.size(); + vector level; + TreeNode* tmp; + for( int i = 0; i < len; i++ ){ + //取一节点放入当前层的结果矢量里 + tmp = q.front(); + q.pop(); + level.push_back(tmp->val); + //当前层所有的节点如果有孩子节点则压入队列 + if(tmp->left){ + q.push(tmp->left); + } + if(tmp->right){ + q.push(tmp->right); + } + } + res.push_back(level); + } + return res; +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题,利用队列做二叉树的层次遍历并保存结果。当然你可以利用堆栈做,但是保存结果的方式不一样而已。 +#### 3.1.1 其他方法 +#### 3.1.1.1 基于堆栈的二叉树层次遍历 +思路还是一致的,只是数据结构换了而已。在每层遍历的时候,需要改动的地方有: +1. 入堆栈要右子树(如果有的话)先入,左子树(如果有的话)后入; +2. 当前层遍历结果 level 要反序再 push_back 至 res。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +基于队列的二叉树层次遍历|O(2^h),h是树的高度|O(n) +基于堆栈的二叉树层次遍历|O(2^h),h是树的高度|O(n),由于多了一步反序,所以会比基于队列的慢一点 +#### 3.1.3 难点分析 +1. 采用什么数据结果做层次遍历 +2. 如何保存每层的遍历结果 +### 3.2 拓展 +如果让你[锯齿形层次遍历](https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/)呢? diff --git a/2018.12.05-leetcode102/Despacito.md b/2018.12.05-leetcode102/Despacito.md new file mode 100644 index 000000000..b34b10c89 --- /dev/null +++ b/2018.12.05-leetcode102/Despacito.md @@ -0,0 +1,57 @@ +# leetcode 102 Binary Tree Level Order Traversal +## 1. Description +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: +```python +[ + [3], + [9, 20], + [15, 7] +] +``` + +## 2. Solution +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def levelOrder(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + if not root: + return [] + l = [root, '#'] + result = [] + level = [] + while len(l) > 1: + curr = l.pop(0) + if curr != '#': + level.append(curr.val) + if curr.left: + l.append(curr.left) + if curr.right: + l.append(curr.right) + else: + l.append('#') + result.append(level) + level = [] + result.append(level) + return result +``` diff --git a/2018.12.05-leetcode102/FFFro.md b/2018.12.05-leetcode102/FFFro.md new file mode 100644 index 000000000..3ea1051f8 --- /dev/null +++ b/2018.12.05-leetcode102/FFFro.md @@ -0,0 +1,27 @@ +import java.util.ArrayList; +import java.util.List; + +class Solution { + public List> levelOrder(TreeNode root) { + List> list = new ArrayList<>(); + if (root == null) { + return list; + } + levelOrder(root,0,list); + return list; + } + + private void levelOrder(TreeNode root, int i, List> list) { + if (root == null) + return; + if (list.size() == i){ + List a = new ArrayList<>(); + a.add(root.val); + list.add(a); + }else { + list.get(i).add(root.val); + } + levelOrder(root.left,i+1,list); + levelOrder(root.right,i+1,list); + } +} diff --git a/2018.12.05-leetcode102/Felix.md b/2018.12.05-leetcode102/Felix.md new file mode 100644 index 000000000..84d34ab21 --- /dev/null +++ b/2018.12.05-leetcode102/Felix.md @@ -0,0 +1,20 @@ +```javascript +public static void levelOrder(Node head){ + if(head == null){ + return; + } + Queue queue = new LinkedList<>(); + queue.offer(head); + while(!queue.isEmpty()){ + head = queue.poll(); + System.out.print(head.value + " "); + if(head.left != null){ + queue.offer(head.left); + } + if(head.right != null){ + queue.offer(head.right); + } + } + } + +``` diff --git a/2018.12.05-leetcode102/GatesMa.md b/2018.12.05-leetcode102/GatesMa.md new file mode 100644 index 000000000..345e13394 --- /dev/null +++ b/2018.12.05-leetcode102/GatesMa.md @@ -0,0 +1,21 @@ +# C++ +```cpp +class Solution { +public: + vector> res; + void check(TreeNode* root, int depth){ + if(root == NULL) return ; + if(res.size() == depth) + { + res.push_back(vector()); + } + res[depth].push_back(root->val); + check(root->left, depth + 1); + check(root->right, depth + 1); + } + vector> levelOrder(TreeNode* root) { + check(root, 0); + return res; + } +}; +``` diff --git a/2018.12.05-leetcode102/Istoryforever.md b/2018.12.05-leetcode102/Istoryforever.md new file mode 100644 index 000000000..f72c7ad8a --- /dev/null +++ b/2018.12.05-leetcode102/Istoryforever.md @@ -0,0 +1,47 @@ +leetcode of 102 +``` +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +struct DataNode{ + TreeNode * p; + int depth; +}; +class Solution { +public: + vector> levelOrder(TreeNode* root) { + vector> ans; + if(root == nullptr) return ans; + queue q; + int depth = 0; + q.push(DataNode{root,depth}); + vectort; + while(!q.empty()){ + DataNode dn = q.front(); + q.pop(); + if(depth == dn.depth){ + t.push_back(dn.p->val); + }else{ + depth = dn.depth; + ans.push_back(t); + t.clear(); + t.push_back(dn.p->val); + } + if(dn.p->left != nullptr) + q.push(DataNode{dn.p->left,depth+1}); + if(dn.p->right != nullptr) + q.push(DataNode{dn.p->right,depth+1}); + + } + ans.push_back(t); + return ans; + + } +}; +``` diff --git a/2018.12.05-leetcode102/MQQM.cpp b/2018.12.05-leetcode102/MQQM.cpp new file mode 100644 index 000000000..8920a14b2 --- /dev/null +++ b/2018.12.05-leetcode102/MQQM.cpp @@ -0,0 +1,48 @@ +/* + 题目: + 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 + + 做法:用队列。 +*/ + +/** + * 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: + vector> levelOrder(TreeNode* root) { + vector> rst; + if(root == NULL){ + return rst; + } + + queue que; + que.push(root); + while( !que.empty() ){ + int len=que.size(); + + vector levelvec; + for(int i=0; ival); + + if(p->left != NULL){ + que.push(p->left); + } + if(p->right != NULL){ + que.push(p->right); + } + } + rst.push_back(levelvec); + } + + return rst; + } +}; diff --git a/2018.12.05-leetcode102/Ostrichcrab.md b/2018.12.05-leetcode102/Ostrichcrab.md new file mode 100644 index 000000000..cdbd8dc5f --- /dev/null +++ b/2018.12.05-leetcode102/Ostrichcrab.md @@ -0,0 +1,33 @@ +``` +/** + * 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: + vector> levelOrder(TreeNode* root) { + vector> result; + queue que; + if(root == nullptr) return result; + que.push(root); + while(!que.empty()){ + int size = que.size(); + vector tmp; + for(int i = 0; i < size; i++){ + TreeNode* t = que.front(); + que.pop(); + tmp.push_back(t->val); + if(t->left) que.push(t->left); + if(t->right) que.push(t->right); + } + result.push_back(tmp); + } + return result; + } +}; +``` diff --git a/2018.12.05-leetcode102/Sagittarius.md b/2018.12.05-leetcode102/Sagittarius.md new file mode 100644 index 000000000..cc0958751 --- /dev/null +++ b/2018.12.05-leetcode102/Sagittarius.md @@ -0,0 +1,40 @@ +``` +/** + * 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: + vector> a; + vector> levelOrder(TreeNode* root) { + if(!root) + return a; + + lot(root,0); + + return a; + } + void lot(TreeNode* node,int level) + { + if(!node) + return; + + if(a.size() v1; + v1.push_back(node->val); + a.push_back(v1); + } + else + a[level].push_back(node->val); + + lot(node->left,level+1); + lot(node->right,level+1); + } +}; +``` diff --git a/2018.12.05-leetcode102/Sunny.md b/2018.12.05-leetcode102/Sunny.md new file mode 100644 index 000000000..e1536c124 --- /dev/null +++ b/2018.12.05-leetcode102/Sunny.md @@ -0,0 +1,22 @@ +```java +class Solution { + + private List> result = new ArrayList<>(); + + public List> levelOrder(TreeNode root) { + levelOrder(root, 0); + return result; + } + + public void levelOrder(TreeNode node, int level) { + if (node != null) { + if (result.size() <= level) { + result.add(new ArrayList()); + } + result.get(level).add(node.val); + levelOrder(node.left, level+1); + levelOrder(node.right, level+1); + } + } +} +``` diff --git a/2018.12.05-leetcode102/TheRocket.md b/2018.12.05-leetcode102/TheRocket.md new file mode 100644 index 000000000..17d530a27 --- /dev/null +++ b/2018.12.05-leetcode102/TheRocket.md @@ -0,0 +1,36 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrder(TreeNode root) { + List> res = new LinkedList<>(); + Queue queue = new LinkedList<>(); + if (root != null) { + queue.offer(root); + } + while (!queue.isEmpty()) { + int size = queue.size(); + List level = new LinkedList<>(); + while (size-- != 0) { + TreeNode node = queue.poll(); + level.add(node.val); + if (node.left != null) { + queue.offer(node.left); + } + if (node.right != null) { + queue.offer(node.right); + } + } + res.add(level); + } + return res; + } +} +``` diff --git a/2018.12.05-leetcode102/Tony the Cyclist.md b/2018.12.05-leetcode102/Tony the Cyclist.md new file mode 100644 index 000000000..4d6ecc469 --- /dev/null +++ b/2018.12.05-leetcode102/Tony the Cyclist.md @@ -0,0 +1,50 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +import java.util.*; +class Solution { + public List> levelOrder(TreeNode root) { + if (root == null){ + return new ArrayList<>(); + } + List> list = new ArrayList<>(); + List tmp = new ArrayList<>(); + ArrayDeque d = new ArrayDeque<>(); + tmp.add(root.val); + list.add(new ArrayList<>(tmp)); + tmp.clear(); + if (root.left != null){ + d.addFirst(root.left); + } + if (root.right != null){ + d.addFirst(root.right); + } + int level = d.size(); + while (!d.isEmpty()){ + TreeNode node = d.pollLast(); + tmp.add(node.val); + level--; + if (node.left != null){ + d.addFirst(node.left); + } + if (node.right != null){ + d.addFirst(node.right); + } + if (level == 0){ + if (!tmp.isEmpty()) + list.add(new ArrayList<>(tmp)); + level = d.size(); + tmp.clear(); + } + } + return list; + } +} +``` diff --git a/2018.12.05-leetcode102/WhiteNight.md b/2018.12.05-leetcode102/WhiteNight.md new file mode 100644 index 000000000..8e2631908 --- /dev/null +++ b/2018.12.05-leetcode102/WhiteNight.md @@ -0,0 +1,80 @@ +>```java +>/** +> * 二叉树的层次遍历1 +> * 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 +> * +> */ +>public class Tree10 +>{ +> public static class TreeNode +> { +> int data; +> TreeNode left; +> TreeNode right; +> +> TreeNode(int val) +> { +> data = val; +> } +> } +> +> public List> levelOrder(TreeNode root) +> { +> //JAVA泛型,List里面存储List,就可以有[[3], [9, 20], [15, 7]] +> List> list = new ArrayList<>(); +> List temp = new ArrayList<>(); +> +> Queue queue = new LinkedList<>(); +> +> if (root != null) +> { +> queue.offer(root); +> } +> +> int width = 1; +> +> while (!queue.isEmpty()) +> { +> TreeNode node = queue.poll(); +> temp.add(node.data); +> width--; +> +> if (node.left != null) +> queue.add(node.left); +> +> if (node.right != null) +> queue.add(node.right); +> +> if (width == 0) +> { +> list.add(temp); +> temp = new ArrayList<>(); +> width = queue.size(); +> } +> +> } +> +> return list; +> } +> +> public static void main(String[] args) +> { +> TreeNode p = new TreeNode(3); +> p.left = new TreeNode(9); +> p.right = new TreeNode(20); +> p.right.left = new TreeNode(15); +> p.right.right = new TreeNode(7); +> +> Tree10 t = new Tree10(); +> +> List> list= t.levelOrder(p); +> for (int i = 0; i < list.size(); i++) +> { +> System.out.print(list.get(i) + " "); +> } +> +> } +> +>} +>``` + diff --git a/2018.12.05-leetcode102/kaizen b/2018.12.05-leetcode102/kaizen new file mode 100644 index 000000000..fafedfa5f --- /dev/null +++ b/2018.12.05-leetcode102/kaizen @@ -0,0 +1,40 @@ +/** + * @author kaizen + * @since 2018-12-07 + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + + class Solution { + + + public List> zigzagLevelOrder(TreeNode root) { + if(root == null) + return new ArrayList<>(); + List> res = new ArrayList<>(); + Queue queue = new LinkedList(); + queue.add(root); + while(!queue.isEmpty()){ + int count = queue.size(); + List list = new ArrayList(); + while(count > 0){ + TreeNode node = queue.poll(); + list.add(node.val); + if(node.left != null) + queue.add(node.left); + if(node.right != null) + queue.add(node.right); + count--; + } + res.add(list); + } + return res; + } + + } + + +} diff --git a/2018.12.05-leetcode102/marguerite.md b/2018.12.05-leetcode102/marguerite.md new file mode 100644 index 000000000..8aaf4a096 --- /dev/null +++ b/2018.12.05-leetcode102/marguerite.md @@ -0,0 +1,70 @@ +102_(二叉树的层次遍历)Binary Tree Level Order Traversal + ## 1 问题描述、输入输出与样例 + ### 1.1 问题描述 + 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
+ ### 1.2 输入与输出 + 输入:
+ * TreeNode* root:二叉树的根节点指针
+ 输出:
+ * vector>:层次遍历的结果,是一个二维矢量的形式 + ### 1.3 样例 + #### 1.3.1 样例1 + 输入: 给定二叉树: [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 + + 输出: + + [ + [3], + [9,20], + [15,7] + ] + +遍历二叉树,首先访问二叉树的第一层元素,再访问第二层,第三层,实现方式,用一个先进先出的队列作为辅助数据结构, +维护一个当前结点数目,和下一层结点数目,当前层遍历层,加入数据集 +public List> levelOrder(TreeNode root){ + List> ret = new ArrayList<>(); + if(root == null) + return ret; + levelOrderCore(root,ret); + return ret; +} + +public void levelOrderCore(Treenode root, List> ret){ + //标记下一行有多少元素 + int nextCount =0; + //当前层有多少结点,为1 是根结点初始化 + int curCount =1; + Queue q= new LinkedList<>(); + q.offer(root); + List tmp = new ArrayList<>(); + while(!q.isEmpty()){ + TreeNode node = q.poll(); + tmp.add(node.val); + //遍历结点当前个数减去1 + curCount--; + if(node.left != null){ + q.offer(node.left); + //左右孩子属于下一层结点 + nextCount++; + } + if(node.right != null){ + q.offer(node.right); + nextCount++; + } + //如果当前层遍历完,加入结果集 + if(curCount ==0){ + curCount = nextCount; + nextCount =0; + ret.add(new ArrayList<>(tmp)); + rmp.clear(); + } + + } + +} diff --git a/2018.12.05-leetcode102/sourcema.md b/2018.12.05-leetcode102/sourcema.md new file mode 100644 index 000000000..ef465d5b6 --- /dev/null +++ b/2018.12.05-leetcode102/sourcema.md @@ -0,0 +1,31 @@ +# LeetCode 102 + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + class Solution { + public List> levelOrder(TreeNode root) { + List> lists = new ArrayList<>(); + if (root == null) { + return lists; + } + dfs(lists, root, 0); + return lists; + } + private static void dfs(List> lists, TreeNode root, int level) { + if (root == null) { + return; + } + if (lists.size() < level + 1) { + lists.add(new ArrayList()); + } + lists.get(level).add(root.val); + dfs(lists,root.left,level+1); + dfs(lists,root.right,level+1); + } + } diff --git a/2018.12.05-leetcode102/syuan.md b/2018.12.05-leetcode102/syuan.md new file mode 100644 index 000000000..5d1acca33 --- /dev/null +++ b/2018.12.05-leetcode102/syuan.md @@ -0,0 +1,95 @@ +##### 题目 +``` +给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 + +例如: +给定二叉树: [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 + +返回其层次遍历结果: + +[ + [3], + [9,20], + [15,7] +] + + +``` +##### 代码 +循环 +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrder(TreeNode root) { + List> resList=new ArrayList<>(); + Queue queue=new LinkedList<>(); + if (root==null) { + return resList; + } + + queue.offer(root); + while(!queue.isEmpty()){ + int length=queue.size(); + List tempList=new ArrayList<>(); + for (int i=0; i> levelOrder(TreeNode root) { + List> res = new ArrayList>(); + levelOrderHelper(res, root, 0); + return res; + } + + public void levelOrderHelper(List> res,TreeNode root,int length){ + if (root==null) { + return; + } + if (length>=res.size()) { + res.add(new ArrayList()); + } + res.get(length).add(root.val); + levelOrderHelper(res,root.left,length+1); + levelOrderHelper(res,root.right,length+1); + } + +} +``` diff --git a/2018.12.05-leetcode102/zjukk.md b/2018.12.05-leetcode102/zjukk.md new file mode 100644 index 000000000..f8702e202 --- /dev/null +++ b/2018.12.05-leetcode102/zjukk.md @@ -0,0 +1,24 @@ +``` +class Solution { +public: + vector> levelOrder(TreeNode* root) { + if (!root) return {}; + queue q; + vector> res; + q.push(root); + while (!q.empty()) { + int cap = q.size(); + vector tmp; + for (int i = 0; i < cap; ++i) { + TreeNode* node = q.front(); + tmp.push_back(node->val); + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + q.pop(); + } + res.push_back(tmp); + } + return res; + } +}; +``` diff --git "a/2018.12.05-leetcode102/\343\200\202V1ncentzzZ.md" "b/2018.12.05-leetcode102/\343\200\202V1ncentzzZ.md" new file mode 100644 index 000000000..305b2ff11 --- /dev/null +++ "b/2018.12.05-leetcode102/\343\200\202V1ncentzzZ.md" @@ -0,0 +1,50 @@ +[102. 二叉树的层次遍历] (https://leetcode-cn.com/problems/binary-tree-level-order-traversal/) + +给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 + +例如: +给定二叉树: [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回其层次遍历结果: + +[ + [3], + [9,20], + [15,7] +] + + +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + // TODO 解题关键:传递树高度 +class Solution { + public List> levelOrder(TreeNode root) { + List> result = new ArrayList<>(); + if(root == null) return result; + executor(root,result,0); + return result; + } + + public void executor(TreeNode node,List> result,int high){ + if(node == null) return; + if(result.size() < high+1) result.add(new ArrayList<>()); + result.get(high).add(node.val); + high++; + executor(node.left,result,high); + executor(node.right,result,high); + } +} +``` diff --git "a/2018.12.05-leetcode102/\343\200\202\343\200\202\343\200\202.md" "b/2018.12.05-leetcode102/\343\200\202\343\200\202\343\200\202.md" new file mode 100644 index 000000000..78037d2a0 --- /dev/null +++ "b/2018.12.05-leetcode102/\343\200\202\343\200\202\343\200\202.md" @@ -0,0 +1,41 @@ +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrder(TreeNode root) { + List> result = new ArrayList<>(); + if (root == null) return result; + Queue queue = new ArrayDeque<>(); + queue.add(root); + List list = new ArrayList(); + int currentLevel = 1,nextLevel = 0; + while (queue.size() != 0){ + TreeNode temp = queue.poll(); + list.add(temp.val); + currentLevel--; + if (temp.left != null){ + queue.add(temp.left); + nextLevel++; + } + if (temp.right != null){ + queue.add(temp.right); + nextLevel++; + } + if (currentLevel == 0){ + result.add(list); + list = new ArrayList<>(); + currentLevel = nextLevel; + nextLevel = 0; + } + } + return result; + } +} +``` diff --git "a/2018.12.05-leetcode102/\344\272\214\345\217\211\346\240\221\347\232\204\345\261\202\346\254\241\351\201\215\345\216\206.md" "b/2018.12.05-leetcode102/\344\272\214\345\217\211\346\240\221\347\232\204\345\261\202\346\254\241\351\201\215\345\216\206.md" new file mode 100644 index 000000000..dbd6e8580 --- /dev/null +++ "b/2018.12.05-leetcode102/\344\272\214\345\217\211\346\240\221\347\232\204\345\261\202\346\254\241\351\201\215\345\216\206.md" @@ -0,0 +1,17 @@ +定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 + +例如: +给定二叉树: [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回其层次遍历结果: + +[ + [3], + [9,20], + [15,7] +] diff --git "a/2018.12.05-leetcode102/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" "b/2018.12.05-leetcode102/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" new file mode 100644 index 000000000..7780e4fbd --- /dev/null +++ "b/2018.12.05-leetcode102/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrder(TreeNode root) { + LinkedList queue = new LinkedList<>(); + List> res = new ArrayList<>(); + if(root == null) return res; + queue.add(root); + while(!queue.isEmpty()){ + int size = queue.size(); + List l = new ArrayList<>(); + for (int i = 0; i < size; i++) { + TreeNode node = queue.remove(); + if(node.left != null) queue.add(node.left); + if(node.right != null) queue.add(node.right); + l.add(node.val); + } + res.add(l); + } + return res; + } + + +} diff --git "a/2018.12.05-leetcode102/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.05-leetcode102/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..b1991045c --- /dev/null +++ "b/2018.12.05-leetcode102/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,44 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + List> res; + List tmp; + public List> levelOrder(TreeNode root) { + res = new ArrayList<>(); + tmp = new ArrayList<>(); + if(root==null)return res; + Queue q = new LinkedList<>(); + q.offer(root); + int left=1; + int next=0; + while(!q.isEmpty()){ + TreeNode r = q.poll(); + left--; + tmp.add(r.val); + if(r.left!=null){ + q.offer(r.left); + next++; + } + if(r.right!=null){ + q.offer(r.right); + next++; + } + if(left==0){ + res.add(tmp); + tmp = new ArrayList<>(); + left=next; + next=0; + } + } + return res; + } +} +``` diff --git "a/2018.12.05-leetcode102/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.12.05-leetcode102/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..289e22a67 --- /dev/null +++ "b/2018.12.05-leetcode102/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,62 @@ +``` +/** +*给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 + +例如: +给定二叉树: [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回其层次遍历结果: + +[ + [3], + [9,20], + [15,7] +] +* +*/ + +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrder(TreeNode root) { + List> res =new ArrayList<>(); + if(root==null){ + return res; + } + + Queue queue=new LinkedList(); + queue.add(root); + TreeNode node=null; + while(!queue.isEmpty()){ + int width=queue.size();//队列的大小就是每一层的宽度 + List list=new ArrayList<>(); + while(width>0){ //按照层的宽度来遍历,每次存放在list中的是当前层从左往右的数字,如果该数字下有子树,则将子树节点存放到队 //列中,作为下一层的要遍历的数字。 + node=queue.poll(); + list.add(node.val); + if(node.left!=null ) + queue.add(node.left); + if(node.right!=null) + queue.add(node.right); + width--; + } + + res.add(list); + } + + return res; + + } +} +``` diff --git "a/2018.12.05-leetcode102/\345\246\256\345\217\257.md" "b/2018.12.05-leetcode102/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..2ebd342c6 --- /dev/null +++ "b/2018.12.05-leetcode102/\345\246\256\345\217\257.md" @@ -0,0 +1,166 @@ +```java +package sy181205; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + + + + + +/** + * @author suyuan + * +给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 + +例如: +给定二叉树: [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回其层次遍历结果: + +[ + [3], + [9,20], + [15,7] +] + + + */ +public class leetcode_102二叉树的层次遍历 +{ + + public static void main(String[] args) + { + TreeNode node1=new TreeNode(1); + TreeNode node2=new TreeNode(2); + TreeNode node3=new TreeNode(3); + TreeNode node4=new TreeNode(4); + TreeNode node5=new TreeNode(5); + + node1.left=node2; + node1.right=node3; + + node2.left=node4; + node2.right=node5; + + node3.left=null; + node3.right=null; + + node4.left=null; + node4.right=null; + node5.left=null; + node5.right=null; + +// List> resList=levelOrder(node1); + List> resList=levelOrder3(node1); + for (List list : resList) + { + for (Integer integer : list) + { + System.out.print(integer+" "); + } + System.out.println(); + } + + + + } + + public static List> levelOrder(TreeNode root) + { + List> result=new ArrayList>(); + if(root==null) + return result; + Queue queue=new LinkedList(); + queue.add(root); + TreeNode node=null; + + while(!queue.isEmpty()) + { + //高度还是要记的...省不了 + int count=queue.size(); + List list=new ArrayList<>(); + while(count>0) + { + node=queue.poll(); + list.add(node.val); + if(node.left!=null ) + queue.add(node.left); + if(node.right!=null) + queue.add(node.right); + count--; + } + + result.add(list); + } + + return result; + + } + + //递归实现 + public static List> levelOrder3(TreeNode root) { + List> res=new ArrayList<>(); + if(root==null) return res; + recursionLevelOrder(root,0,res); + return res; + } + private static void recursionLevelOrder(TreeNode root,int level,List> res){ + if(root==null) return; + if(res.size()==level){ + List subres=new ArrayList<>(); + subres.add(root.val); + res.add(subres); + }else{ + res.get(level).add(root.val); + } + recursionLevelOrder(root.left,level+1,res); + recursionLevelOrder(root.right,level+1,res); + } + + public static List> levelOrder1(TreeNode root) + { + List> result=new ArrayList>(); + if(root==null) + return result; + Queue queue=new LinkedList(); + queue.add(root); + TreeNode node=null; + + while(!queue.isEmpty()) + { + List list=new ArrayList<>(); + while(!queue.isEmpty()) + { + node=queue.poll(); + list.add(node.val); + } + if(node.left!=null && node.right!=null) + queue.add(node.left); + if(node.right!=null && node.right!=null) + queue.add(node.right); + result.add(list); + } + + return result; + + } + + +} + + class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } +``` diff --git "a/2018.12.05-leetcode102/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.05-leetcode102/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..8360054c4 --- /dev/null +++ "b/2018.12.05-leetcode102/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,40 @@ +### [102. Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/description/) + +**题目描述** +> 层次遍历二叉树。逐层,从左向右。 + +**例子** +略 + +**思想** +辅助队列 + +**解法** +```python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def levelOrder(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + res = [] + queue = [root] + while queue and root: + row = [] + for _ in range(len(queue)): + node = queue.pop(0) + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + row.append(node.val) + res.append(row) + return res +``` \ No newline at end of file diff --git "a/2018.12.05-leetcode102/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.05-leetcode102/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..8255331fb --- /dev/null +++ "b/2018.12.05-leetcode102/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,44 @@ +``` +public class levelOrderInBinaryTree { + public class TreeNode{ + int value; + TreeNode left; + TreeNode right; + public TreeNode(int value) { + this.value = value; + } + } + + public List> levelOrder(TreeNode root){ + List> list = new ArrayList<>();//存放一棵树 + List tempList = new ArrayList<>();//存放一层的值 + if(root == null){ + return list; + } + Queue queue = new LinkedList<>(); + queue.add(root); + int toBePrint = 1;//当前层要打印的节点数 + int nextLevelCount = 0;//下一层要打印的节点数 + while(queue.isEmpty() == false){ + TreeNode temp = queue.poll(); + tempList.add(temp.value); + toBePrint--; + if(temp.left!=null){ + queue.add(temp.left); + nextLevelCount++; + } + if(temp.right!=null){ + queue.add(temp.right); + nextLevelCount++; + } + if(toBePrint==0){ //打印完本层的节点,做善后工作 + list.add(new ArrayList<>(tempList)); + tempList.clear(); + toBePrint = nextLevelCount; + nextLevelCount=0; + } + } + return list; + } +} +``` diff --git "a/2018.12.05-leetcode102/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.05-leetcode102/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..44a188e0b --- /dev/null +++ "b/2018.12.05-leetcode102/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,45 @@ +``` +/** + * 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: + vector> levelOrder(TreeNode* root) { + vector> ret; + if(!root) return ret; + + queue q; + q.push(root); + + while(!q.empty()) + { + int n = q.size(); + vector tmp; + + while(n>0) + { + TreeNode *node = q.front(); + q.pop(); + n--; + + tmp.push_back(node->val); + if(node->left) + q.push(node->left); + if(node->right) + q.push(node->right); + + } + + ret.push_back(tmp); + } + + return ret; + } +}; +``` diff --git "a/2018.12.05-leetcode102/\350\216\216\350\216\216.md" "b/2018.12.05-leetcode102/\350\216\216\350\216\216.md" new file mode 100644 index 000000000..eb7761f27 --- /dev/null +++ "b/2018.12.05-leetcode102/\350\216\216\350\216\216.md" @@ -0,0 +1,24 @@ +``` +class Solution: + def levelOrder(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + q = [root] + v = [] + if not root: + return [] + while q: + templist = [] + templen = len(q) + for i in range(templen): + temp = q.pop(0) + templist.append(temp.val) + if temp.left: + q.append(temp.left) + if temp.right: + q.append(temp.right) + v.append(templist) + return v +``` diff --git "a/2018.12.05-leetcode102/\351\223\201\347\224\267\347\245\236sama.md" "b/2018.12.05-leetcode102/\351\223\201\347\224\267\347\245\236sama.md" new file mode 100644 index 000000000..cd768d5a2 --- /dev/null +++ "b/2018.12.05-leetcode102/\351\223\201\347\224\267\347\245\236sama.md" @@ -0,0 +1,214 @@ + + + + +## 101.对称二叉树 + +> [https://leetcode-cn.com/problems/binary-tree-level-order-traversal/](https://leetcode-cn.com/problems/binary-tree-level-order-traversal/) + +### 一、题目 + +给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 + +例如:给定二叉树: `[3,9,20,null,null,15,7]`, + +``` + 3 + / \ + 9 20 + / \ + 15 7 +``` + +返回其层次遍历结果: + +``` + [ + [3], + [9,20], + [15,7] + ] +``` + +### 二、思路 + +- **层序遍历回顾:** 用队列。将根结点入队,只要队列不为空,就每次从队列中出队一个结点,打印它的值,如果当前出队的这个结点有左孩子,左孩子入队,有右孩子,则右孩子入队。 + + ```java + /*不换行*/ + public void printByLevel(TreeNode root) { + if(root==null)return; + Queue q = new LinkedList<>(); + q.offer(root); + + while(!q.isEmpty()) { + TreeNode popNow = q.poll(); + System.out.print(popNow.val); + System.out.print(" "); + if(popNow.left!=null) { + q.offer(popNow.left); + } + if(popNow.right!=null) { + q.offer(popNow.right); + } + } + System.out.println(); + } + /*换行: + 层序遍历打印二叉树是个很简单的问题,但是此题要求换行,不是简单的层序遍历了。关键问题就是需要去确定何时该换行。这就需要两个TreeNode类型的变量last和nLast。last表示正在打印的当前行最右节点,nLast表示下一行的最右结点。*/ + public void printBylevel1(TreeNode root) { + if (root == null) + return; + + Queue q = new LinkedList<>(); + int level = 1; + TreeNode last = root; + TreeNode nLast = null; + q.offer(root); + System.out.printf("Level%d:", level++); + while (!q.isEmpty()) { + TreeNode popNow = q.poll(); + System.out.print(popNow.val + " "); + + if (popNow.left != null) { + q.offer(popNow.left); + nLast = popNow.left; + } + if (popNow.right != null) { + q.offer(popNow.right); + nLast = popNow.right; + } + if (popNow == last && !q.isEmpty()) { + last = nLast; + System.out.printf("\nLevel%d:", level++); + } + } + System.out.println(); + } + ``` + + + +### 三、题解 + +#### 这是第一次ac:首先想到的是左神教的last和nlast做法,没能一次成功。于是画图,发现列队size()配合上BFS就能解出本题。 + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { int val; TreeNode + * left; TreeNode right; TreeNode(int x) { val = x; } } + */ +class Solution { + public List> breadthTraverse(TreeNode root) { + List> listAll = new ArrayList<>(); + Queue q = new LinkedList<>(); + q.offer(root); + if(root==null)return listAll; + while (!q.isEmpty()) { + List list = new ArrayList<>(); + int size = q.size(); + for (int i = 0; i < size; i++) { + //System.out.printf("size=%d\n",size); + TreeNode popNow = q.poll(); + list.add(popNow.val); + if (popNow.left != null) { + q.offer(popNow.left); + } + if (popNow.right != null) { + q.offer(popNow.right); + } + } + listAll.add(list); + } + return listAll; + } +} +``` + +#### 这是第二次ac:比较蠢,非要用左神的last和nlast,这回倒好了,直接解析String。。怎么说呢,有点无脑,好在8ms还可以接受。 + +```java + public List> levelOrder(TreeNode root) { + List> listAll = new ArrayList<>(); + if (root == null) + return listAll; + String s = printBylevel2(root); + String[] sArray = s.split("\n"); + for (int i = 0; i < sArray.length; i++) { + List list = new ArrayList(); + for (String ss : sArray[i].split(" ")) { + list.add(Integer.parseInt(ss)); + } + listAll.add(list); + } + // System.out.println("TorF?"); + return listAll; + } + + public String printBylevel2(TreeNode root) { + if (root == null) + return ""; + StringBuilder sb = new StringBuilder(); + Queue q = new LinkedList<>(); + int level = 1; + TreeNode last = root; + TreeNode nLast = null; + q.offer(root); + + while (!q.isEmpty()) { + TreeNode popNow = q.poll(); + sb.append(popNow.val + " "); + + if (popNow.left != null) { + q.offer(popNow.left); + nLast = popNow.left; + } + if (popNow.right != null) { + q.offer(popNow.right); + nLast = popNow.right; + } + if (popNow == last && !q.isEmpty()) { + last = nLast; + sb.append("\n"); + } + } + return sb.toString(); + } +``` + +#### 这是第三次ac:在上面的基础上,发现了小秘密,其实只要在左神的解法上稍作改动就能完成此题。 + +```java +public List> levelOrder(TreeNode root) { + List> listAll = new ArrayList<>(); + if (root == null) + return listAll; + Queue q = new LinkedList<>(); + int level = 1; + TreeNode last = root; + TreeNode nLast = null; + q.offer(root); + List list = new ArrayList(); + while (!q.isEmpty()) { + int size = q.size(); + TreeNode popNow = q.poll(); + list.add(popNow.val); + if (popNow.left != null) { + q.offer(popNow.left); + nLast = popNow.left; + } + if (popNow.right != null) { + q.offer(popNow.right); + nLast = popNow.right; + } + if (popNow == last) { + last = nLast; + listAll.add(list); + list=new ArrayList(); + } + } + return listAll; + } +``` + diff --git "a/2018.12.05-leetcode102/\351\230\263.md" "b/2018.12.05-leetcode102/\351\230\263.md" new file mode 100644 index 000000000..81b01afd1 --- /dev/null +++ "b/2018.12.05-leetcode102/\351\230\263.md" @@ -0,0 +1,37 @@ +class Solution { + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } + } + + public List> levelOrder(TreeNode root) { + List> list = new LinkedList>(); + if(root == null) { + return list; + } + Queue queue = new LinkedList(); + queue.add(root); + + while(!queue.isEmpty()) { + List sublist = new LinkedList(); + int size = queue.size(); + for(int i = 0; i < size; i++) { + TreeNode currentNode = queue.poll(); + sublist.add(currentNode.val); + if(currentNode.left!=null) { + queue.add(currentNode.left); + } + if(currentNode.right!=null) { + queue.add(currentNode.right); + } + } + list.add(sublist); + } + return list; + } +} diff --git a/2018.12.06-leetcode103/-.md b/2018.12.06-leetcode103/-.md new file mode 100644 index 000000000..77edefb39 --- /dev/null +++ b/2018.12.06-leetcode103/-.md @@ -0,0 +1,33 @@ +public class Solution_103 { + public List> zigzagLevelOrder(TreeNode root) { + List> result = new ArrayList<>(); + + List list = new ArrayList<>(); + if(root==null) + return result; + list.add(root); + boolean flag = false; + while (list.size() != 0) { + List temp = new ArrayList<>(); + List list2 = new ArrayList<>(); + + for (TreeNode node : list) { + temp.add(node.val); + if (node.left != null) + list2.add(node.left); + if (node.right != null) + list2.add(node.right); + if (!flag) { + Collections.reverse(list2); + } + + } + flag = !flag; + result.add(temp); + list=list2; + } + + return result; + + } +} diff --git "a/2018.12.06-leetcode103/103. \344\272\214\345\217\211\346\240\221\347\232\204\351\224\257\351\275\277\345\275\242\345\261\202\346\254\241\351\201\215\345\216\206.md" "b/2018.12.06-leetcode103/103. \344\272\214\345\217\211\346\240\221\347\232\204\351\224\257\351\275\277\345\275\242\345\261\202\346\254\241\351\201\215\345\216\206.md" new file mode 100644 index 000000000..155bceea4 --- /dev/null +++ "b/2018.12.06-leetcode103/103. \344\272\214\345\217\211\346\240\221\347\232\204\351\224\257\351\275\277\345\275\242\345\261\202\346\254\241\351\201\215\345\216\206.md" @@ -0,0 +1,17 @@ +给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 + +例如: +给定二叉树: [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回其层次遍历结果: + +[ + [3], + [9,20], + [15,7] +] diff --git a/2018.12.06-leetcode103/Avalon.md b/2018.12.06-leetcode103/Avalon.md new file mode 100644 index 000000000..5df87e019 --- /dev/null +++ b/2018.12.06-leetcode103/Avalon.md @@ -0,0 +1,44 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + List> result = new ArrayList<>(); + if (root == null) return result; + LinkedList queue = new LinkedList<>(); + queue.add(root); + TreeNode current; + List tempilist; + int ilistlen; + boolean isleftbegin = true; + while (!queue.isEmpty()) { + List intlist = new ArrayList<>(); + int qlen = queue.size(); + for (int i = 0; i < qlen; i++) { + current = queue.poll(); + intlist.add(current.val); + if (current.left != null) + queue.add(current.left); + if (current.right != null) + queue.add(current.right); + } + if (!isleftbegin) { + tempilist = new ArrayList<>(); + ilistlen = intlist.size(); + for (int i=0;i +### 1.2 输入与输出 +输入:
+* TreeNode* root:二叉树的根节点指针
+输出:
+* vector>:锯齿形层次遍历的结果,是一个二维矢量的形式 +### 1.3 样例 +#### 1.3.1 样例1 +输入: 给定二叉树: [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 + +输出: + + [ + [3], + [20,9], + [15,7] + ] + +## 2 思路描述与代码 +### 2.1 思路描述(基于队列的二叉树层次遍历) +二叉树的层次遍历可以利用队列来做,其思路也很简单。
+这里为了把每层的结果记录下来,对BFS的代码结构稍微改动了下,即里面用了个 for 循环做当前层遍历。
+其次与102层次遍历不一样的是,这里使用 depth 记录深度,在深度 depth 为偶数的时候对当前层次遍历结果进行反转再插入 res 中。 +```cpp +初始化二叉树层次遍历的二维矢量 res ; +头结点入队; +深度初始化为0; +while( 队列不空 ){ + 初始化当前层的遍历结果 level; + 获取当前层的数目数 len; + for( int i = 0; i < len; i++ ){ + 取出当前层的节点tmp并保存至 level; + 左右孩子非空则入队; + } + 如果深度为偶数则反转 level; + 将 level 保存至 res ; +} +返回 res ; +``` +比如给定二叉树: [3,9,20,null,null,15,7];
+首先根节点3入队,然后进入 while 循环;
+此时队列不空,深度为1,有1个元素3,for 循环后有 res = {[3]}, 队列里面有元素[9, 20];
+此时队列不空,深度为2,有元素[9, 20],反转后为[20, 9], for 循环后有 res = {[3],[20,9]}, 队列里面有元素[15, 7];
+此时队列不空,深度为3,有元素[15, 7],for 循环后有 res = {[3],[20,9], [15,7]}, 队列里面没有元素;
+此时队列空后,返回 res = {[3],[20,9], [15,7]} 。 + +### 2.2 代码 +```cpp +vector> zigzagLevelOrder(TreeNode* root) { + vector> res; + if(root == nullptr) + return res; + //基于队列做层序遍历 + queue q; + q.push(root); + //层序遍历的深度 + int depth = 1; + while( !q.empty() ){ + //保存当前层遍历的结果 + vector layer; + //获取当前层的节点数目 + int layer_size = q.size(); + //遍历当前的所有层 + for( int i = 0; i < layer_size; i++ ){ + TreeNode* tmp = q.front(); + q.pop(); + //如果左右子树非空,则入队 + if(tmp->left) + q.push(tmp->left); + if(tmp->right) + q.push(tmp->right); + layer.push_back(tmp->val); + } + //将当前层遍历的结果存到res里面,同时深度加1 + if((depth & 0x01) == 0) reverse(layer.begin(), layer.end()); + res.push_back(layer); + depth += 1; + } + return res; + } +``` +## 3 思考与拓展 +### 3.1 思考 +本题,主要考察的还是数据结构。这里为了简单,直接对深度为偶数层的遍历结果直接反转。你也可以使用双端队列或者奇层用队列、偶层用堆栈。 +#### 3.1.1 其他方法 +#### 3.1.1.1 基于双端队列的二叉树锯齿形层次遍历 +思路还是一致的,只是数据结构换了而已。
+在 depth 为奇数的时候从队头出队;
+在 depth 为偶数的时候从队尾出队;
+#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +基于队列的二叉树层次遍历|O(2^h),h是树的高度|O(n) +基于双端队列的二叉树锯齿形层次遍历|O(2^h),h是树的高度|O(n),由于不需要反序,所以会比基于队列的二叉树层次遍历快一点 +#### 3.1.3 难点分析 +1. 采用何种数据结果保存不同方式的层遍历结果 +### 3.2 拓展 +如果让你结合队列和堆栈做锯齿形层次遍历呢? diff --git a/2018.12.06-leetcode103/Despacito.md b/2018.12.06-leetcode103/Despacito.md new file mode 100644 index 000000000..e4440f8ee --- /dev/null +++ b/2018.12.06-leetcode103/Despacito.md @@ -0,0 +1,61 @@ +# LeetCode 103 Binary Tree Zigzag Level Order Traversal +## 1. Description +Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). + +For example: +Given binary tree [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 + +return its zigzag level order traversal as: +```python +[ + [3], + [20,9], + [15,7] +] +``` +## 2. Solution +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def zigzagLevelOrder(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + if not root: + return [] + l = [root, '#'] + result = [] + level = [] + flag = 1 + while len(l) > 1: + curr = l.pop(0) + if curr != '#': + if flag == 1: + level.append(curr.val) + else: + level.insert(0, curr.val) + if curr.left: + l.append(curr.left) + if curr.right: + l.append(curr.right) + else: + l.append('#') + result.append(level) + level = [] + flag *= -1 + result.append(level) + return result +``` diff --git a/2018.12.06-leetcode103/FFFro.md b/2018.12.06-leetcode103/FFFro.md new file mode 100644 index 000000000..3673185f4 --- /dev/null +++ b/2018.12.06-leetcode103/FFFro.md @@ -0,0 +1,26 @@ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + List> list = new ArrayList<>(); + if (root == null) { + return list; + } + levelOrder(root,list,0); + return list; + } + + private void levelOrder(TreeNode root, List> list, int level) { + if (root == null) + return; + if (level == list.size()){ + List temp = new LinkedList<>(); + list.add(temp); + } + if (level % 2 == 0) + list.get(level).add(root.val); + else + list.get(level).add(0,root.val); + + levelOrder(root.left, list,level+1); + levelOrder(root.right, list,level+1); + } +} diff --git a/2018.12.06-leetcode103/Felix.md b/2018.12.06-leetcode103/Felix.md new file mode 100644 index 000000000..454cb2f69 --- /dev/null +++ b/2018.12.06-leetcode103/Felix.md @@ -0,0 +1,42 @@ +```javascript +public ArrayList> zigzagLevelOrder(TreeNode root) { + ArrayList> res = new ArrayList>(); + Stack stack1 = new Stack(); + Stack stack2 = new Stack(); + int layer = 1;//层数 + stack1.push(root); + while(!stack1.isEmpty() || !stack2.isEmpty()){ + if(layer%2!=0){//奇数层 + ArrayList list = new ArrayList(); + while(!stack1.isEmpty()){ + TreeNode node = stack1.pop(); + if(node != null){ + list.add(node.val); + stack2.push(node.left);//从左到右 + stack2.push(node.right); + } + } + if(!list.isEmpty()){ + res.add(list); + layer++; + } + }else{//偶数层 + ArrayList list = new ArrayList(); + while(!stack2.isEmpty()){ + TreeNode node = stack2.pop(); + if(node != null){ + list.add(node.val); + stack1.push(node.right);//从右到左 + stack1.push(node.left); + } + } + if(!list.isEmpty()){ + res.add(list); + layer++; + } + } + } + + return res; + } +``` diff --git a/2018.12.06-leetcode103/GatesMa.md b/2018.12.06-leetcode103/GatesMa.md new file mode 100644 index 000000000..686d4697e --- /dev/null +++ b/2018.12.06-leetcode103/GatesMa.md @@ -0,0 +1,42 @@ +# c++ +```cpp +/** + * 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: + vector> zigzagLevelOrder(TreeNode* root) { + vector> res; + queue q; + if(root == NULL) return res; + q.push(root); + bool rever = false;//代表当前在第几层 + while(!q.empty()) {//每次循环都是一层 + vector t; // 临时数组 + //q temq; + int len = q.size(); + for(int i=0;i < len;i++){ + TreeNode*temNode = q.front(); + q.pop(); + t.push_back(temNode->val); + if(temNode->left) q.push(temNode->left); + if(temNode->right) q.push(temNode->right); + //t.push_back(temNode->val); + } + + if(rever) { + reverse(t.begin(), t.end()); + } + res.push_back(t); + rever = !rever; + } + return res; + } +}; +``` diff --git a/2018.12.06-leetcode103/Istoryforever.md b/2018.12.06-leetcode103/Istoryforever.md new file mode 100644 index 000000000..ecf1f4e61 --- /dev/null +++ b/2018.12.06-leetcode103/Istoryforever.md @@ -0,0 +1,55 @@ +leetcode of 103 +``` +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +struct DN{ + TreeNode * p; + int depth; +}; +class Solution { +public: + vector> zigzagLevelOrder(TreeNode* root) { + vector> ans; + if(root == nullptr) return ans; + bool flag = true; + int depth = 0; + queue q; + vectort; + q.push(DN{root,0}); + while(!q.empty()){ + DN dn = q.front(); + q.pop(); + if(dn.depth == depth){ + t.push_back(dn.p->val); + }else{ + depth = dn.depth; + if(!flag) reverse(t.begin(),t.end()); + ans.push_back(t); + flag=!flag; + t.clear(); + t.push_back(dn.p->val); + } + + if(dn.p->left) q.push(DN{dn.p->left,depth+1}); + if(dn.p->right) q.push(DN{dn.p->right,depth+1}); + + if(q.empty()) + { + if(!flag) reverse(t.begin(),t.end()); + ans.push_back(t); + } + } + + return ans; + + + } +}; +``` diff --git a/2018.12.06-leetcode103/MQQM.cpp b/2018.12.06-leetcode103/MQQM.cpp new file mode 100644 index 000000000..84b8ea584 --- /dev/null +++ b/2018.12.06-leetcode103/MQQM.cpp @@ -0,0 +1,56 @@ +/* + 题目: + 给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 + + 做法:判断是奇数层还是偶数层。 +*/ + +/** + * 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: + vector> zigzagLevelOrder(TreeNode* root) { + vector> rst; + if(root==NULL){ + return rst; + } + + queue que; + que.push(root); + bool even=false; + while( !que.empty() ){ + int len=que.size(); + + vector levelvec; + for(int i=0; ival); + + if(p->left != NULL){ + que.push(p->left); + } + if(p->right != NULL){ + que.push(p->right); + } + } + + if(even){//偶数层 + reverse(levelvec.begin(), levelvec.end()); + even=false; + }else{ + even=true; + } + rst.push_back(levelvec); + } + + return rst; + } +}; diff --git a/2018.12.06-leetcode103/Ostrichcrab.md b/2018.12.06-leetcode103/Ostrichcrab.md new file mode 100644 index 000000000..b5c6c67ea --- /dev/null +++ b/2018.12.06-leetcode103/Ostrichcrab.md @@ -0,0 +1,36 @@ +``` +/** + * 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: + vector> zigzagLevelOrder(TreeNode* root) { + vector> result; + queue que; + if(root == NULL) return result; + que.push(root); + while(!que.empty()){ + vector tmp; + int size = que.size(); + for(int i = 0; i < size; i++){ + TreeNode* t = que.front(); + que.pop(); + tmp.push_back(t->val); + if(t->left) que.push(t->left); + if(t->right) que.push(t->right); + } + result.push_back(tmp); + } + for(int i = 0; i < result.size(); i++){ + if(i&1) reverse(result[i].begin(),result[i].end()); + } + return result; + } +}; +``` diff --git a/2018.12.06-leetcode103/Sagittarius.md b/2018.12.06-leetcode103/Sagittarius.md new file mode 100644 index 000000000..83af0a43f --- /dev/null +++ b/2018.12.06-leetcode103/Sagittarius.md @@ -0,0 +1,44 @@ +``` +/** + * 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: + vector> a; + vector> zigzagLevelOrder(TreeNode* root) { + if(!root) + return a; + + lot(root,0); + + for(int i=0;i v1; + v1.push_back(node->val); + a.push_back(v1); + } + else + a[level].push_back(node->val); + + + lot(node->left,level+1); + lot(node->right,level+1); + + } +}; +``` diff --git a/2018.12.06-leetcode103/Sunny.md b/2018.12.06-leetcode103/Sunny.md new file mode 100644 index 000000000..e14821795 --- /dev/null +++ b/2018.12.06-leetcode103/Sunny.md @@ -0,0 +1,25 @@ +```java +class Solution { + List> result = new ArrayList<>(); + public List> zigzagLevelOrder(TreeNode root) { + zigzagLevelOrder(root, 0, false); + return result; + } + + public void zigzagLevelOrder(TreeNode node, int level, boolean inverse) { + if (node != null) { + if (result.size() <= level) { + result.add(new ArrayList<>()); + } + if (inverse) { + result.get(level).add(0, node.val); + } + else { + result.get(level).add(node.val); + } + zigzagLevelOrder(node.left, level+1, !inverse); + zigzagLevelOrder(node.right, level+1, !inverse); + } + } +} +``` diff --git a/2018.12.06-leetcode103/TheRocket.md b/2018.12.06-leetcode103/TheRocket.md new file mode 100644 index 000000000..164d4d0d5 --- /dev/null +++ b/2018.12.06-leetcode103/TheRocket.md @@ -0,0 +1,42 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + List> res = new LinkedList<>(); + Queue queue = new LinkedList<>(); + if (root != null) { + queue.offer(root); + } + boolean leftToRight = true; + while (!queue.isEmpty()) { + int size = queue.size(); + LinkedList level = new LinkedList<>(); + while (size-- != 0) { + TreeNode node = queue.poll(); + if (leftToRight) { + level.offerLast(node.val); + } else { + level.offerFirst(node.val); + } + if (node.left != null) { + queue.offer(node.left); + } + if (node.right != null) { + queue.offer(node.right); + } + } + res.add(level); + leftToRight = !leftToRight; + } + return res; + } +} +``` diff --git a/2018.12.06-leetcode103/Tony the Cyclist.md b/2018.12.06-leetcode103/Tony the Cyclist.md new file mode 100644 index 000000000..a2f8aae63 --- /dev/null +++ b/2018.12.06-leetcode103/Tony the Cyclist.md @@ -0,0 +1,93 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +import java.util.*; + +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + List> list = new ArrayList<>(); + if (root == null){ + return list; + } + ArrayDeque d = new ArrayDeque<>(); + ArrayList tmp = new ArrayList<>(); + d.addFirst(root); + tmp.add(root.val); + int flag = 0; + tmp.clear(); + int level = 1; + while (!d.isEmpty()){ + TreeNode node = d.pollLast(); + tmp.add(node.val); + level --; + if (node.left != null){ + d.addFirst(node.left); + } + if (node.right != null){ + d.addFirst(node.right); + } + if (level == 0){ + if (flag == 0){ + flag = 1; + } + else if (flag == 1){ + Collections.reverse(tmp); + flag = 0; + } + list.add(new ArrayList<>(tmp)); + level = d.size(); + tmp.clear(); + } + } + return list; + } +} +``` + +```python +from collections import deque +class Solution(object): + def zigzagLevelOrder(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + if root == None: + return [] + elif root.right == None and root.left == None: + return [[root.val]] + d = deque([]) + result = [[root.val]] + d.appendleft(root.left) + d.appendleft(root.right) + flag = 0 + level = 2 + tmp = [] + while len(d) != 0: + node = d.pop() + level -= 1 + if node != None: + tmp.append(node.val) + if node.left != None: + d.appendleft(node.left) + if node.right != None: + d.appendleft(node.right) + if level == 0: + if flag == 1: + result.append(tmp) + flag = 0 + else: + tmp.reverse() + result.append(tmp) + flag = 1 + tmp = [] + level = len(d) + return result +``` diff --git a/2018.12.06-leetcode103/Typing.txt b/2018.12.06-leetcode103/Typing.txt new file mode 100644 index 000000000..441e1b520 --- /dev/null +++ b/2018.12.06-leetcode103/Typing.txt @@ -0,0 +1,72 @@ +public class Main103 { + + public static void main(String[] args){ + Main103 main = new Main103(); + main.test(); + } + + public void test(){ + TreeNode root = new TreeNode(3); + root.left = new TreeNode(9); + root.right = new TreeNode(20); + root.right.left = new TreeNode(15); + root.right.right = new TreeNode(7); + List> res = zigzagLevelOrder(root); + for (List integerList:res){ + System.out.println(Arrays.toString(integerList.toArray())); + } + } + + public List> zigzagLevelOrder(TreeNode root) { + if (root==null) + return new ArrayList<>(); + LinkedList linkedList = new LinkedList<>(); + linkedList.add(root); + boolean reverse = false; + LinkedList tmpList = new LinkedList(); + List>result = new ArrayList<>(); + while (!linkedList.isEmpty()){ + TreeNode tmpNode; + List curList = new ArrayList<>(); + tmpList.clear(); + while (true) { + if (!reverse) { + tmpNode = linkedList.pollFirst(); + curList.add(tmpNode.val); + if (tmpNode.left!=null){ + tmpList.add(tmpNode.left); + } + if (tmpNode.right!=null){ + tmpList.add(tmpNode.right); + } + } else { + tmpNode = linkedList.pollLast(); + curList.add(tmpNode.val); + if (tmpNode.right!=null) + tmpList.offerFirst(tmpNode.right); + if (tmpNode.left!=null) + tmpList.offerFirst(tmpNode.left); + } + if (linkedList.isEmpty()) + break; + } + reverse = !reverse; + if (!curList.isEmpty()){ + result.add(curList); + } + if (!tmpList.isEmpty()){ + linkedList.addAll(tmpList); + } + } + return result; + } + + private class TreeNode{ + int val; + TreeNode left; + TreeNode right; + TreeNode(int x){ + val = x; + } + } +} diff --git a/2018.12.06-leetcode103/WhiteNight.md b/2018.12.06-leetcode103/WhiteNight.md new file mode 100644 index 000000000..eae0bdf43 --- /dev/null +++ b/2018.12.06-leetcode103/WhiteNight.md @@ -0,0 +1,84 @@ +```java +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +/** + * 给定一个二叉树,返回其节点值的锯齿形层次遍历。 + * 即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行 + * + */ +public class Tree15 { + public static class TreeNode { + int data; + TreeNode left; + TreeNode right; + + TreeNode(int val) { + data = val; + } + } + + public List> zigzagLevelOrder(TreeNode root) { + TreeNode pNode = root; + Stack stack1 = new Stack<>(); + Stack stack2 = new Stack<>(); + List list = new ArrayList<>(); + List> resultList = new ArrayList<>(); + + if (pNode == null) + return resultList; + + stack1.push(pNode); + + while (!stack1.isEmpty() || !stack2.isEmpty()){ + while (!stack1.isEmpty()){ + TreeNode tempNode = stack1.pop(); + if (tempNode.left != null){ + stack2.push(tempNode.left); + } + if (tempNode.right != null){ + stack2.push(tempNode.right); + } + list.add(tempNode.data); + if (stack1.isEmpty()){ + resultList.add(new ArrayList<>(list)); + list.clear(); + } + } + + while (!stack2.isEmpty()){ + TreeNode tempNode = stack2.pop(); + if (tempNode.right != null){ + stack1.push(tempNode.right); + } + if (tempNode.left != null){ + stack1.push(tempNode.left); + } + list.add(tempNode.data); + if (stack2.isEmpty()){ + resultList.add(new ArrayList<>(list)); + list.clear(); + } + } + } + + return resultList; + } + + public static void main(String[] args) { + TreeNode p = new TreeNode(4); + p.left = new TreeNode(9); + p.right = new TreeNode(20); + p.right.left = new TreeNode(15); + p.right.right = new TreeNode(7); + + Tree15 t = new Tree15(); + List> list= t.zigzagLevelOrder(p); + + for (int i = 0; i < list.size(); i++) { + System.out.print(list.get(i) + " "); + } + } +} +``` \ No newline at end of file diff --git a/2018.12.06-leetcode103/sourcema.md b/2018.12.06-leetcode103/sourcema.md new file mode 100644 index 000000000..e520d5034 --- /dev/null +++ b/2018.12.06-leetcode103/sourcema.md @@ -0,0 +1,35 @@ +# leetcode 103 + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + class Solution { + public List> zigzagLevelOrder(TreeNode root) { + List> lists = new ArrayList<>(); + if (root == null) { + return lists; + } + dfs(lists, root, 0); + return lists; + } + private static void dfs(List> lists, TreeNode root, int level) { + if (root == null) { + return; + } + if (lists.size() < level + 1) { + lists.add(new ArrayList()); + } + if (((level + 1) & 1) == 0) { + lists.get(level).add(0,root.val); + }else { + lists.get(level).add(root.val); + } + dfs(lists,root.left,level+1); + dfs(lists,root.right,level+1); + } + } diff --git a/2018.12.06-leetcode103/syuan.md b/2018.12.06-leetcode103/syuan.md new file mode 100644 index 000000000..59de803c7 --- /dev/null +++ b/2018.12.06-leetcode103/syuan.md @@ -0,0 +1,98 @@ +##### 题目 + +``` +给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 + +例如: +给定二叉树 [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 + +返回锯齿形层次遍历如下: + +[ + [3], + [20,9], + [15,7] +] +``` +#### 代码 +##### 两个栈 + +``` +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + List> resList=new ArrayList<>(); + Stack stack1=new Stack<>(); + Stack stack2=new Stack<>(); + if (root==null) { + return resList; + } + + stack1.push(root); + int index=1; + while(!stack1.isEmpty() || !stack2.isEmpty()){ + int length1=stack1.size(); + int length2=stack2.size(); + List tempList=new ArrayList<>(); + if (index%2!=0) { + for (int i=0; i> zigzagLevelOrder(TreeNode root) { + List> res=new ArrayList<>(); + zigzagLevelOrderHelp(res,root,0); + return res; + } + + public void zigzagLevelOrderHelp(List> res,TreeNode root,int index){ + if (root==null) return; + + if (res.size()<=index) { + res.add(new ArrayList<>()); + } + if (index%2==0) { + res.get(index).add(root.val); + }else{ + res.get(index).add(0,root.val); + } + zigzagLevelOrderHelp(res,root.left,index+1); + zigzagLevelOrderHelp(res,root.right,index+1); + } +} +``` +> add(index,int) 该函数可以对一个数组进行前序插入 其余的会往后挪动 diff --git a/2018.12.06-leetcode103/zjukk.md b/2018.12.06-leetcode103/zjukk.md new file mode 100644 index 000000000..af8ead3bc --- /dev/null +++ b/2018.12.06-leetcode103/zjukk.md @@ -0,0 +1,18 @@ +``` +class Solution { +public: + vector> zigzagLevelOrder(TreeNode* root) { + vector> res; + bfs(res,root,0,true); + return res; + } + void bfs(vector>& res, TreeNode* root, int level, bool fromLeft) { + if (!root) return; + if (level == res.size()) res.push_back({}); + if (fromLeft) res[level].push_back(root->val); + else res[level].insert(res[level].begin(),root->val); + bfs(res,root->left,level+1,!fromLeft); + bfs(res,root->right,level+1,!fromLeft); + } +}; +``` diff --git "a/2018.12.06-leetcode103/\343\200\202V1ncentzzZ.md" "b/2018.12.06-leetcode103/\343\200\202V1ncentzzZ.md" new file mode 100644 index 000000000..4cbec534d --- /dev/null +++ "b/2018.12.06-leetcode103/\343\200\202V1ncentzzZ.md" @@ -0,0 +1,51 @@ +[103. 二叉树的锯齿形层次遍历](https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/) + +给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 + +例如: +给定二叉树 [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回锯齿形层次遍历如下: + +[ + [3], + [20,9], + [15,7] +] + +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + List> result = new ArrayList<>(); + if(root == null) return result; + executor(root, result, 0); + return result; + } + + public void executor(TreeNode node,List> result,int high){ + if(node == null) return; + if(result.size() <= high) result.add(new ArrayList<>()); + if(high % 2 == 0){ + result.get(high).add(node.val); + }else { + result.get(high).add(0,node.val); + } + executor(node.left, result, high+1); + executor(node.right, result, high+1); + } +} +``` diff --git "a/2018.12.06-leetcode103/\343\200\202\343\200\202\343\200\202.md" "b/2018.12.06-leetcode103/\343\200\202\343\200\202\343\200\202.md" new file mode 100644 index 000000000..05a8ba1b9 --- /dev/null +++ "b/2018.12.06-leetcode103/\343\200\202\343\200\202\343\200\202.md" @@ -0,0 +1,50 @@ +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + List> result = new ArrayList<>(); + if (root == null) return result; + Queue queue = new ArrayDeque<>(); + queue.add(root); + List list = new ArrayList(); + int currentLevel = 1,nextLevel = 0; + boolean isReverse = false; + while (queue.size() != 0){ + TreeNode temp = queue.poll(); + list.add(temp.val); + currentLevel--; + if (temp.left != null){ + queue.add(temp.left); + nextLevel++; + } + if (temp.right != null){ + queue.add(temp.right); + nextLevel++; + } + if (currentLevel == 0){ + List list1 = new ArrayList<>(); + if (isReverse){ + for (int i = list.size()-1; i >= 0; i--){ + list1.add(list.get(i)); + } + list = list1; + } + isReverse = !isReverse; + result.add(list); + list = new ArrayList<>(); + currentLevel = nextLevel; + nextLevel = 0; + } + } + return result; + } +} +``` diff --git "a/2018.12.06-leetcode103/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" "b/2018.12.06-leetcode103/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" new file mode 100644 index 000000000..0167f6cb7 --- /dev/null +++ "b/2018.12.06-leetcode103/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + LinkedList queue = new LinkedList<>(); + List> res = new ArrayList<>(); + if (root == null) return res; + queue.add(root); + int mark = 0; + while(!queue.isEmpty()) { + int size = queue.size(); + List l = new ArrayList<>(); + if (mark == 0) { + for (int i = 0; i < size; i++) { + TreeNode node = queue.remove(); + if(node.left != null) queue.add(node.left); + if(node.right != null) queue.add(node.right); + l.add(node.val); + } + mark = 1; + } else { + LinkedList stack = new LinkedList<>(); + for (int i = 0; i < size; i++) { + TreeNode node = queue.remove(); + if(node.left != null) queue.add(node.left); + if(node.right != null) queue.add(node.right); + stack.push(node); + } + while(!stack.isEmpty()) { + l.add(stack.pop().val); + } + mark = 0; + } + res.add(l); + } + return res; + } +} diff --git "a/2018.12.06-leetcode103/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.06-leetcode103/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..54aadbcbc --- /dev/null +++ "b/2018.12.06-leetcode103/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,52 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + List> res = new ArrayList<>(); + if(root==null)return res; + Stack s1 = new Stack<>(); + Stack s2 = new Stack<>(); + s1.push(root); + List tmp = new ArrayList<>(); + while(!s1.empty()){ + while(!s1.empty()){ + TreeNode r = s1.pop(); + tmp.add(r.val); + if(r.left!=null){ + s2.push(r.left); + } + if(r.right!=null){ + s2.push(r.right); + } + if(s1.empty()){ + res.add(tmp); + tmp = new ArrayList<>(); + } + } + while(!s2.empty()){ + TreeNode r = s2.pop(); + tmp.add(r.val); + if(r.right!=null){ + s1.push(r.right); + } + if(r.left!=null){ + s1.push(r.left); + } + if(s2.empty()){ + res.add(tmp); + tmp = new ArrayList<>(); + } + } + } + return res; + } +} +``` diff --git "a/2018.12.06-leetcode103/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.12.06-leetcode103/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..e51aff8cf --- /dev/null +++ "b/2018.12.06-leetcode103/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,67 @@ +``` +/** +给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 + +例如: +给定二叉树 [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回锯齿形层次遍历如下: + +[ + [3], + [20,9], + [15,7] +] + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + List> res=new ArrayList<>(); + if(root==null){ + return res; + } + Queue queue=new LinkedList(); + TreeNode temp=null; + int width=0; + boolean flag=true; + queue.offer(root); + while(!queue.isEmpty()){ + List list=new ArrayList<>(); + width=queue.size(); + while(width>0){ + temp=queue.poll(); + list.add(temp.val); + if(temp.left!=null){ + queue.offer(temp.left); + } + if(temp.right!=null){ + queue.offer(temp.right); + } + + width--; + } + if(flag){ //在102题目的代码的基础上,在这里设置标志位。 + res.add(list); + flag=false; + }else{ //为false的时候,反转集合;只能说不能再菜了,不知道有这个简便方法 + Collections.reverse(list); + res.add(list); + flag=true; + } + } + + return res; + } +} +``` diff --git "a/2018.12.06-leetcode103/\345\246\256\345\217\257.md" "b/2018.12.06-leetcode103/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..db72652e3 --- /dev/null +++ "b/2018.12.06-leetcode103/\345\246\256\345\217\257.md" @@ -0,0 +1,129 @@ +```java +package sy181206; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + + + + + +/** + * @author suyuan + * +给定一个二叉树,返回其节点值的锯齿形层次遍历。 +(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 + +例如: +给定二叉树 [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回锯齿形层次遍历如下: + +[ + [3], + [20,9], + [15,7] +] + + */ +public class leetcode_103二叉树的锯齿形层次遍历 +{ + + public static void main(String[] args) + { + TreeNode node1=new TreeNode(1); + TreeNode node2=new TreeNode(2); + TreeNode node3=new TreeNode(3); + TreeNode node4=new TreeNode(4); + TreeNode node5=new TreeNode(5); + + node1.left=node2; + node1.right=node3; + + node2.left=node4; + node2.right=node5; + + node3.left=null; + node3.right=null; + + node4.left=null; + node4.right=null; + node5.left=null; + node5.right=null; + +// List> resList=levelOrder(node1); + List> resList=zigzagLevelOrder(node1); + for (List list : resList) + { + for (Integer integer : list) + { + System.out.print(integer+" "); + } + System.out.println(); + } + + } + + public static List> zigzagLevelOrder(TreeNode root) + { + List> result=new ArrayList>(); + if(root==null) + return result; + Queue queue=new LinkedList(); + queue.add(root); + TreeNode node=null; + //true从左往右 + boolean flag=true; + + while(!queue.isEmpty()) + { + //高度还是要记的...省不了 + int count=queue.size(); + List list=new ArrayList<>(); + while(count>0) + { + node=queue.poll(); + list.add(node.val); + if(node.left!=null ) + queue.add(node.left); + if(node.right!=null) + queue.add(node.right); + count--; + } + + if(flag) + { + result.add(list); + flag=false; + } + else + { + Collections.reverse(list); + result.add(list); + flag=true; + } + + } + + return result; + } + +} + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +``` diff --git "a/2018.12.06-leetcode103/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.06-leetcode103/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..5e888ed44 --- /dev/null +++ "b/2018.12.06-leetcode103/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,44 @@ +#### [103. Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/) +**题目描述** +> zigzag锯齿形层次遍历二叉树。(逐层,从左向右;然后下一层是从右向左) + +**例子** +略 + +**思想** +辅助队列 + Flag翻转标志 + +**解法** +```python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def zigzagLevelOrder(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + Flag = 1 + res = [] + queue = [root] + while queue and root: + row = [] + for _ in range(len(queue)): + node = queue.pop(0) + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + row.append(node.val) + if Flag == 1: + res.append(row) + else: + res.append(row[::-1]) + Flag *= (-1) + return res +``` \ No newline at end of file diff --git "a/2018.12.06-leetcode103/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.06-leetcode103/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..6dfdc8b9c --- /dev/null +++ "b/2018.12.06-leetcode103/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,47 @@ +``` +/** + * 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: + vector> zigzagLevelOrder(TreeNode* root) { + vector> ret; + if(!root) return ret; + + queue q; + q.push(root); + bool flag = true; + + while(!q.empty()) + { + int n = q.size(); + vector tmp; + + while(n>0) + { + TreeNode *node = q.front(); + q.pop(); + n--; + + tmp.push_back(node->val); + if(node->left) q.push(node->left); + if(node->right) q.push(node->right); + + } + + if(!flag) + reverse(tmp.begin(), tmp.end()); + flag = !flag; + ret.push_back(tmp); + } + + return ret; + } +}; +``` diff --git "a/2018.12.06-leetcode103/\350\216\216\350\216\216.md" "b/2018.12.06-leetcode103/\350\216\216\350\216\216.md" new file mode 100644 index 000000000..f56267056 --- /dev/null +++ "b/2018.12.06-leetcode103/\350\216\216\350\216\216.md" @@ -0,0 +1,44 @@ +``` +from collections import deque +class Solution: + def zigzagLevelOrder(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + q = deque([root]) + v = [] + j = 1 + if not root: + return [] + while q: + j+=1 + if j%2==0: + templist = [] + templen = len(q) + for i in range(templen): + temp = q.popleft() + templist.append(temp.val) + if temp.left: + q.append(temp.left) + if temp.right: + q.append(temp.right) + + v.append(templist) + else: + templist = [] + templen = len(q) + for i in range(templen): + temp = q.pop() + templist.append(temp.val) + if temp.right: + q.appendleft(temp.right) + if temp.left: + q.appendleft(temp.left) + + + v.append(templist) + + + return v +``` diff --git "a/2018.12.06-leetcode103/\351\223\201\347\224\267\347\245\236sama.md" "b/2018.12.06-leetcode103/\351\223\201\347\224\267\347\245\236sama.md" new file mode 100644 index 000000000..499964517 --- /dev/null +++ "b/2018.12.06-leetcode103/\351\223\201\347\224\267\347\245\236sama.md" @@ -0,0 +1,150 @@ +## 103.锯齿打印(ZigZag)二叉树 + +> [https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/](https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/) + +### 一、题目 + +给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 + +例如:给定二叉树 `[3,9,20,null,null,15,7]`, + +``` + 3 + / \ + 9 20 + / \ + 15 7 +``` + +返回锯齿形层次遍历如下: + +``` + [ + [3], + [20,9], + [15,7] + ] +``` + +### 二、思路 + +- 就是用一个双端队列(或者两个栈)和一个flag标志 +- 具体描述:从左到右时,让结点从队列头弹出,该结点的孩子从队尾进入;从右到左时,从队尾弹出结点,该结点的孩子从队头进入。 +- + +### 三、题解 + +#### 第一次ac:就是 思路描述的双端队列方法,当然也可以用两个栈实现。 + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { int val; TreeNode + * left; TreeNode right; TreeNode(int x) { val = x; } } + */ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + List> listAll = new ArrayList<>(); + if(root==null)return listAll; + Deque q = new LinkedList<>(); + q.offerFirst(root); + boolean flag = true; + while (!q.isEmpty()) { + List list = new ArrayList<>(); + int size = q.size();//本层结点个数 + for (int i = 0; i < size; i++) { + TreeNode popNow; + if (flag) { + popNow = q.pollFirst(); + if (popNow.left != null) { + q.offerLast(popNow.left); + } + if (popNow.right != null) { + q.offerLast(popNow.right); + } + }else { + popNow = q.pollLast(); + if (popNow.right != null) { + q.offerFirst(popNow.right); + } + if (popNow.left != null) { + q.offerFirst(popNow.left); + } + } + list.add(popNow.val); + } + listAll.add(list); + flag=!flag; + } + return listAll; + } +} +``` + +#### 第二解:在leetcode上提交看到的答案,主要方法是:用当前层数来控制从左还是从右开始,(上面的是用flag标志,都差不多);没想到的是他用了个list.add(0,node.val),方便了很多。 + +```java + public List> zigzagLevelOrder(TreeNode root) { + List> listAll = new ArrayList<>(); + if(root == null)return listAll; + Queue queue = new LinkedList(); + queue.add(root); + int depth = 0; + while(!queue.isEmpty()){ + int count = queue.size(); + List list = new ArrayList(); + while(count > 0){ + TreeNode node = queue.poll(); + if(depth%2 == 1){ + list.add(0,node.val); + }else{ + list.add(node.val); + } + if(node.left != null) queue.add(node.left); + if(node.right != null) queue.add(node.right); + count--; + } + depth++; + listAll.add(list); + } + return listAll; + } +``` + +#### 第三解:leetcode上的,用了这个Collections.reverse(list) ,虽然我想提高自己造轮子的能力,尽量不用库函数解题,但不得不承认,这些东西还是挺方便的。 + +```java +public List> zigzagLevelOrder(TreeNode root) { + List> listAll = new ArrayList>(); + if (root == null) return result; + Queue q = new LinkedList(); + q.add(root); + TreeNode node = null; + boolean flag = true; + while (!queue.isEmpty()) { + int count = queue.size(); + List list = new ArrayList<>(); + while (count > 0) { + node = queue.poll(); + list.add(node.val); + if (node.left != null) + queue.add(node.left); + if (node.right != null) + queue.add(node.right); + count--; + } + if (flag) { + listAll.add(list); + flag = false; + } else { + Collections.reverse(list); + listAll.add(list); + flag = true; + } + } + return listAll; + } +``` + + + diff --git a/2018.12.07-leetcode104/-.md b/2018.12.07-leetcode104/-.md new file mode 100644 index 000000000..0367ffc85 --- /dev/null +++ b/2018.12.07-leetcode104/-.md @@ -0,0 +1,14 @@ +public class Solution_104 { + public int maxDepth(TreeNode root) { + int max = 0; + if (null == root) { + return 0; + } + max = 1; + int left = maxDepth(root.left); + int right = maxDepth(root.right); + max = Math.max(left,right)+1; + + return max; + } +} diff --git "a/2018.12.07-leetcode104/104. \344\272\214\345\217\211\346\240\221\347\232\204\346\234\200\345\244\247\346\267\261\345\272\246" "b/2018.12.07-leetcode104/104. \344\272\214\345\217\211\346\240\221\347\232\204\346\234\200\345\244\247\346\267\261\345\272\246" new file mode 100644 index 000000000..8409bb189 --- /dev/null +++ "b/2018.12.07-leetcode104/104. \344\272\214\345\217\211\346\240\221\347\232\204\346\234\200\345\244\247\346\267\261\345\272\246" @@ -0,0 +1,15 @@ +给定一个二叉树,找出其最大深度。 + +二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 + +说明: 叶子节点是指没有子节点的节点。 + +示例: +给定二叉树 [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回它的最大深度 3 。 diff --git a/2018.12.07-leetcode104/Avalon.md b/2018.12.07-leetcode104/Avalon.md new file mode 100644 index 000000000..3e9ec9ad2 --- /dev/null +++ b/2018.12.07-leetcode104/Avalon.md @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) return 0; + int nodedeep = 0; + LinkedList list = new LinkedList<>(); + list.add(root); + TreeNode current; + int len; + List intlist = new ArrayList<>(); + while (!list.isEmpty()) { + len = list.size(); + for (int i = 0; i < len; i++) { + current = list.poll(); + if (current.left!=null) + list.add(current.left); + if (current.right!=null) + list.add(current.right); + } + nodedeep++; + } + return nodedeep; + } +} diff --git a/2018.12.07-leetcode104/Be a fresh man.md b/2018.12.07-leetcode104/Be a fresh man.md new file mode 100644 index 000000000..fa850c402 --- /dev/null +++ b/2018.12.07-leetcode104/Be a fresh man.md @@ -0,0 +1,93 @@ +## 104_Maximum Depth of Binary Tree(二叉树的最大深度) +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定一个二叉树,找出其最大深度。
+二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
+__说明__: 叶子节点是指没有子节点的节点。 +### 1.2 输入与输出 +输入: +* TreeNode* root:二叉树的根节点 + +输出: +* int:最远叶子节点的最长路径上的节点数 +### 1.3 样例 +#### 1.3.1 样例1 +输入: 给定二叉树:[3,9,20,null,null,15,7] + + 3 + / \ + 9 20 + / \ + 15 7 + +输出: 3 + +## 2 思路描述与代码 +### 2.1 思路描述(基于队列的层次遍历方法) +利用队列做层次遍历,遍历的时候用 depth 记录当前层遍历的深度,遍历结束后返回其深度。 +```cpp +初始化深度 depth 为0; +将二叉树根节点压入队列; +while( 队列不空 ){ + 深度 depth 加1 + 获取当前层的深度 layer_len + + for( int i = 0; i < layer_len; i++ ){ + 弹出一个节点; + 如果该节点有孩子节点,则入队; + } +} +返回 depth; +``` +### 2.2 代码 +```cpp +int maxDepth(TreeNode* root) { + queue q; + //初始化深度为0 + int depth = 0; + //将头结点压入队列 + if(root) + q.push(root); + //利用队列做二叉树的层次遍历 + while( !q.empty() ){ + //深度加1 + depth += 1; + //获取当前层的深度 + int layer_len = q.size(); + //层次遍历的所有节点 + //如果该节点有孩子节点,则入队 + for( int i = 0; i < layer_len; i++ ){ + TreeNode* tmp = q.front(); + q.pop(); + if(tmp->left) + q.push(tmp->left); + + if(tmp->right) + q.push(tmp->right); + } + } + return depth; +} +``` +## 3 思考与拓展 +### 3.1 思考 +有了101、102、103题的练手,本题就是易如反掌。本方法可以看做BFS,那当然还有一种DFS的做法了。 +#### 3.1.1 其他方法 +#### 3.1.1.1 递归法 +根节点的深度就是其左子树和右子树的深度的最大值加1。 +```cpp +int maxDepth(TreeNode* root) { + if(root == nullptr) return 0; + else return max(maxDepth(root->left), maxDepth(root->right)) + 1; +} +``` +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +基于队列的层次遍历方法|O(2^h),h是树的高度|O(n) +递归法|O(n)|O(n) +#### 3.1.3 难点分析 +1. 使用递归方法时要得到递归的公式 +2. 使用队列方法时需要注意深度加1的条件必须是当前层所有节点遍历结束。 +### 3.2 拓展 +如果让你求最远叶子节点的最长路径呢? diff --git a/2018.12.07-leetcode104/Despacito.md b/2018.12.07-leetcode104/Despacito.md new file mode 100644 index 000000000..a3cf8ba0e --- /dev/null +++ b/2018.12.07-leetcode104/Despacito.md @@ -0,0 +1,44 @@ +# LeetCode 104 Maximum Depth of Binary Tree +## 1. Description + +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. + +Note: A leaf is a node with no children. + +Example: + +Given binary tree [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 + +return its depth = 3. + +## 2. Solution + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def maxDepth(self, root): + """ + :type root: TreeNode + :rtype: int + """ + if root == None: + return 0 + else: + left = self.maxDepth(root.left) + right = self.maxDepth(root.right) + return max(left, right) + 1 +``` \ No newline at end of file diff --git a/2018.12.07-leetcode104/FFFro.md b/2018.12.07-leetcode104/FFFro.md new file mode 100644 index 000000000..8940c73a1 --- /dev/null +++ b/2018.12.07-leetcode104/FFFro.md @@ -0,0 +1,15 @@ +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) + return 0; + return depth(root); + } + + private int depth(TreeNode root) { + if (root == null) + return 0; + int left = depth(root.left); + int right = depth(root.right); + return left > right ? left+1 : right+1; + } +} diff --git a/2018.12.07-leetcode104/GatesMa.md b/2018.12.07-leetcode104/GatesMa.md new file mode 100644 index 000000000..495dcef3c --- /dev/null +++ b/2018.12.07-leetcode104/GatesMa.md @@ -0,0 +1,24 @@ +# c++ +```cpp +/** + * 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: + int maxDepth(TreeNode* root) { + return depth(root); + } + int depth(TreeNode* root) { + if(root == NULL) return 0; + int l = depth(root->left); + int r = depth(root->right); + return l > r ? l + 1 : r + 1; + } +}; +``` diff --git a/2018.12.07-leetcode104/Istoryforever.md b/2018.12.07-leetcode104/Istoryforever.md new file mode 100644 index 000000000..90607c3f3 --- /dev/null +++ b/2018.12.07-leetcode104/Istoryforever.md @@ -0,0 +1,24 @@ +leetcode of 104 +``` +/** + * 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: + int maxDepth(TreeNode* root) { + if(root == nullptr){ + return 0; + } + int l = maxDepth(root->left); + int r = maxDepth(root->right); + int m = l > r ? l : r; + return m+1; + } +}; +``` diff --git a/2018.12.07-leetcode104/MQQM.cpp b/2018.12.07-leetcode104/MQQM.cpp new file mode 100644 index 000000000..0f5f65966 --- /dev/null +++ b/2018.12.07-leetcode104/MQQM.cpp @@ -0,0 +1,24 @@ +/* + 题目: + 给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数 +*/ + +/** + * 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: + int maxDepth(TreeNode* root) { + if(root==NULL) + return 0; + int leftDepth = maxDepth(root->left); + int rightDepth = maxDepth(root->right); + return (leftDepth > rightDepth) ? leftDepth+1 : rightDepth+1 ; + } +}; diff --git a/2018.12.07-leetcode104/Ostrichcrab.md b/2018.12.07-leetcode104/Ostrichcrab.md new file mode 100644 index 000000000..6e373ef79 --- /dev/null +++ b/2018.12.07-leetcode104/Ostrichcrab.md @@ -0,0 +1,18 @@ +``` +/** + * 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: + int maxDepth(TreeNode* root) { + if(root==NULL) return 0; + return max(maxDepth(root->left),maxDepth(root->right))+1; + } +}; +``` diff --git a/2018.12.07-leetcode104/Sagittarius.md b/2018.12.07-leetcode104/Sagittarius.md new file mode 100644 index 000000000..ee639bf38 --- /dev/null +++ b/2018.12.07-leetcode104/Sagittarius.md @@ -0,0 +1,39 @@ +``` +/** + * 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: + vector a; + int maxDepth(TreeNode* root) { + if(!root) + return 0; + lot(root,0); + + return a.size(); + + } + void lot(TreeNode* node,int level) + { + if(!node) + return ; + if(a.size()left,level+1); + lot(node->right,level+1); + } + +}; +static int optimize = []() { + ios::sync_with_stdio(false); + cin.tie(nullptr); + cout.tie(nullptr); + return 0; +}(); +``` diff --git a/2018.12.07-leetcode104/Saul.md b/2018.12.07-leetcode104/Saul.md new file mode 100644 index 000000000..01cb83090 --- /dev/null +++ b/2018.12.07-leetcode104/Saul.md @@ -0,0 +1,22 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + if(root == null){ + return 0; + } + int leftLen = maxDepth(root.left); + int rightLen = maxDepth(root.right); + return Math.max(leftLen,rightLen)+1; + + } +} +``` diff --git a/2018.12.07-leetcode104/Sunny.md b/2018.12.07-leetcode104/Sunny.md new file mode 100644 index 000000000..aeb001050 --- /dev/null +++ b/2018.12.07-leetcode104/Sunny.md @@ -0,0 +1,15 @@ +```java +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) return 0; + return Math.max(maxDepth(root.left, 1), maxDepth(root.right, 1)); + } + + public int maxDepth(TreeNode node, int level) { + if (node != null) { + level = Math.max(maxDepth(node.left, level+1), maxDepth(node.right, level+1)); + } + return level; + } +} +``` diff --git a/2018.12.07-leetcode104/TheRocket.md b/2018.12.07-leetcode104/TheRocket.md new file mode 100644 index 000000000..4962d5b50 --- /dev/null +++ b/2018.12.07-leetcode104/TheRocket.md @@ -0,0 +1,19 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) { + return 0; + } + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); + } +} +``` diff --git a/2018.12.07-leetcode104/Tony the Cyclist.md b/2018.12.07-leetcode104/Tony the Cyclist.md new file mode 100644 index 000000000..9428e4940 --- /dev/null +++ b/2018.12.07-leetcode104/Tony the Cyclist.md @@ -0,0 +1,25 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + int left; + int right; + if (root == null){ + return 0; + } + else { + left = maxDepth(root.left) + 1; + right = maxDepth(root.right) + 1; + } + return left > right ? left : right; + } +} +``` diff --git a/2018.12.07-leetcode104/Typing.txt b/2018.12.07-leetcode104/Typing.txt new file mode 100644 index 000000000..7bba0d79f --- /dev/null +++ b/2018.12.07-leetcode104/Typing.txt @@ -0,0 +1,36 @@ +public class Main104 { + public static void main(String[] args){ + Main104 main = new Main104(); + main.test(); + } + + public void test(){ + TreeNode root = new TreeNode(3); + root.left = new TreeNode(9); + root.right = new TreeNode(20); + root.right.left = new TreeNode(15); + root.right.right = new TreeNode(7); + System.out.println(maxDepth(root)); + } + + public int maxDepth(TreeNode root) { + int leftDep,rightDep,max; + if (root!=null){ + leftDep = maxDepth(root.left); + rightDep = maxDepth(root.right); + max = leftDep>rightDep?leftDep:rightDep; + return max+1; + } + return 0; + } + + private class TreeNode{ + int val; + TreeNode left; + TreeNode right; + TreeNode(int x){ + val = x; + } + } + +} diff --git a/2018.12.07-leetcode104/WhiteNight.md b/2018.12.07-leetcode104/WhiteNight.md new file mode 100644 index 000000000..6cc2b767c --- /dev/null +++ b/2018.12.07-leetcode104/WhiteNight.md @@ -0,0 +1,49 @@ +>```java +>/** +> * 给定一个二叉树,找出其最大深度。 +> * +> * 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 +> * +> * 说明: 叶子节点是指没有子节点的节点。 +> * +> */ +>public class Tree1 +>{ +> public static class TreeNode +> { +> int data; +> TreeNode left; +> TreeNode right; +> TreeNode(int val) +> { +> data = val; +> } +> } +> +> public int maxDepth(TreeNode root) +> { +> if (root == null) +> return 0; +> +> int nleft = maxDepth(root.left); +> int nright = maxDepth(root.right); +> +> return nleft > nright ? nleft + 1 : nright + 1; +> } +> +> public static void main(String[] args) +> { +> TreeNode p = new TreeNode(1); +> p.left = new TreeNode(2); +> p.right = new TreeNode(3); +> p.left.left = null; +> p.left.right = null; +> p.right.left = new TreeNode(4); +> p.right.right = new TreeNode(5); +> +> Tree1 t = new Tree1(); +> System.out.println(t.maxDepth(p)); +> } +>} +>``` + diff --git a/2018.12.07-leetcode104/disappo1nted.md b/2018.12.07-leetcode104/disappo1nted.md new file mode 100644 index 000000000..8f4b301b0 --- /dev/null +++ b/2018.12.07-leetcode104/disappo1nted.md @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int maxDepth(TreeNode root) + { + return Depth(root); + } + public int Depth(TreeNode root) + { + if(root==null) + return 0; + int left = maxDepth(root.left); + int right = maxDepth(root.right); + return left>right?left+1:right+1; + } + +} diff --git a/2018.12.07-leetcode104/fish.md b/2018.12.07-leetcode104/fish.md new file mode 100644 index 000000000..86b272972 --- /dev/null +++ b/2018.12.07-leetcode104/fish.md @@ -0,0 +1,30 @@ +``` +public class Solution { + public static int deepOfTree(TreeNode treeNode, int level){ + if (treeNode == null) { + return level; + } + int left = deepOfTree(treeNode.getLeft(), level + 1); + int right = deepOfTree(treeNode.getRight(), level + 1); + return left > right ? left : right; + } + public static void main(String[] args) { + TreeNode r4r = new TreeNode(21, null, null); + TreeNode r4l = new TreeNode(22, null, null); + + TreeNode r3r = new TreeNode(7, null, null); + TreeNode r3l = new TreeNode(15, r4l, r4r); + TreeNode l2r = new TreeNode(20, r3l, r3r); + TreeNode l2l = new TreeNode(9, null, null); + TreeNode root = new TreeNode(3, l2l, l2r); + System.out.println(deepOfTree(root, 0)); + } +} +@Data +@AllArgsConstructor +@NoArgsConstructor +class TreeNode{ + private int val; + private TreeNode left; + private TreeNode right; +} \ No newline at end of file diff --git a/2018.12.07-leetcode104/justwe.md b/2018.12.07-leetcode104/justwe.md new file mode 100644 index 000000000..a88bc6e64 --- /dev/null +++ b/2018.12.07-leetcode104/justwe.md @@ -0,0 +1,11 @@ +class Solution { + public int maxDepth(TreeNode root) { + if(root==null) + return 0; + else{ + int lTree = maxDepth(root.left); + int rTree = maxDepth(root.right); + return java.lang.Math.max(lTree, rTree)+1; + } + } +} diff --git a/2018.12.07-leetcode104/sourcema.md b/2018.12.07-leetcode104/sourcema.md new file mode 100644 index 000000000..7ef792550 --- /dev/null +++ b/2018.12.07-leetcode104/sourcema.md @@ -0,0 +1,28 @@ +# leetcode 104 + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + class Solution { + public int maxDepth(TreeNode root) { + if (root == null) { + return 0; + } + return getDepth(root,0); + } + public static int getDepth(TreeNode root,int level) { + if (root == null) { + return level; + } + int left = getDepth(root.left, level + 1); + int right = getDepth(root.right, level + 1); + return Math.max(left,right); + } + + + } diff --git a/2018.12.07-leetcode104/syuan.md b/2018.12.07-leetcode104/syuan.md new file mode 100644 index 000000000..9f757d312 --- /dev/null +++ b/2018.12.07-leetcode104/syuan.md @@ -0,0 +1,20 @@ +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) { + return 0; + } + + return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; + } +} +``` diff --git a/2018.12.07-leetcode104/zjukk.md b/2018.12.07-leetcode104/zjukk.md new file mode 100644 index 000000000..23bedcbe3 --- /dev/null +++ b/2018.12.07-leetcode104/zjukk.md @@ -0,0 +1,11 @@ +``` +class Solution { +public: + int maxDepth(TreeNode* root) { + if (!root) return 0; + int left = maxDepth(root->left); + int right = maxDepth(root->right); + return max(left,right)+1; + } +}; +``` diff --git "a/2018.12.07-leetcode104/\343\200\202V1ncentzzZ.md" "b/2018.12.07-leetcode104/\343\200\202V1ncentzzZ.md" new file mode 100644 index 000000000..0ecf3ba86 --- /dev/null +++ "b/2018.12.07-leetcode104/\343\200\202V1ncentzzZ.md" @@ -0,0 +1,51 @@ +[104. 二叉树的最大深度][https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/] + +给定一个二叉树,找出其最大深度。 + +二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 + +说明: 叶子节点是指没有子节点的节点。 + +示例: +给定二叉树 [3,9,20,null,null,15,7], +``` + 3 + / \ + 9 20 + / \ + 15 7 +``` +返回它的最大深度 3 。 + +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { +// public int maxDepth(TreeNode root) { +// if(root == null) return 0; +// return getDepth(root.left,root.right,1); +// } + +// public int getDepth(TreeNode node1,TreeNode node2,int high){ +// if(node1 == null && node2 == null) return high; +// high++; +// if(node1 == null) return getDepth(node2.left,node2.right,high); +// if(node2 == null) return getDepth(node1.left,node1.right,high); +// return Math.max(getDepth(node1.left,node1.right,high),getDepth(node2.left,node2.right,high)); +// } + + public int maxDepth(TreeNode root) { + if(root == null) return 0; + int left = maxDepth(root.left); + int right = maxDepth(root.right); + return 1 + (left > right ? left : right); + } +} +``` diff --git "a/2018.12.07-leetcode104/\343\200\202\343\200\202\343\200\202.md" "b/2018.12.07-leetcode104/\343\200\202\343\200\202\343\200\202.md" new file mode 100644 index 000000000..2d776ea73 --- /dev/null +++ "b/2018.12.07-leetcode104/\343\200\202\343\200\202\343\200\202.md" @@ -0,0 +1,27 @@ +``` + public int maxDepth(TreeNode root) { + int dept = 0; + if (root == null)return dept; + Queue queue = new ArrayDeque<>(); + queue.add(root); + int currentLevel = 1,nextLevel = 0; + while (queue.size() != 0){ + TreeNode temp = queue.poll(); + currentLevel--; + if (temp.left != null){ + queue.add(temp.left); + nextLevel++; + } + if (temp.right != null){ + queue.add(temp.right); + nextLevel++; + } + if (currentLevel == 0){ + currentLevel = nextLevel; + nextLevel = 0; + dept++; + } + } + return dept; + } +``` diff --git "a/2018.12.07-leetcode104/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" "b/2018.12.07-leetcode104/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" new file mode 100644 index 000000000..90a0dca6e --- /dev/null +++ "b/2018.12.07-leetcode104/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" @@ -0,0 +1,15 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) return 0; + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); + } +} diff --git "a/2018.12.07-leetcode104/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.07-leetcode104/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..d9b5ee91d --- /dev/null +++ "b/2018.12.07-leetcode104/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,40 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + if(root==null)return 0; + Queue q = new LinkedList<>(); + q.add(root); + int level = 0; + int next=0; + int last=1; + while(!q.isEmpty()){ + TreeNode r = q.poll(); + last--; + if(r.left!=null){ + q.add(r.left); + next++; + } + if(r.right!=null){ + q.add(r.right); + next++; + } + + if(last==0){ + level++; + last=next; + next=0; + } + } + return level; + } +} +``` diff --git "a/2018.12.07-leetcode104/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.12.07-leetcode104/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..d6e296562 --- /dev/null +++ "b/2018.12.07-leetcode104/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,69 @@ +``` +/** +给定一个二叉树,找出其最大深度。 + +二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 + +说明: 叶子节点是指没有子节点的节点。 + +示例: +给定二叉树 [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回它的最大深度 3 。 + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + List> res =new ArrayList<>(); + if(root==null){ + return 0; + } + Queue queue=new LinkedList(); + queue.add(root); + TreeNode node=null; + while(!queue.isEmpty()){ + int width=queue.size();//队列的大小就是每一层的宽度 + List list=new ArrayList<>(); + while(width>0){ //按照层的宽度来遍历,每次存放在list中的是当前层从左往右的数字,如果该数字下有子树,则将子树节点存放到队列中,作为下一 // 层的要遍历的数字。 + node=queue.poll(); + list.add(node.val); + if(node.left!=null ) + queue.add(node.left); + if(node.right!=null) + queue.add(node.right); + width--; + } + res.add(list); + } + + return res.size();//沿用之前的代码,返回集合的大小即可 + + } +} +// 递归实现 +class Solution { + public int maxDepth(TreeNode root) { + //为空就返回0;不为空,高度等于左子树或者右子树中最大的那个高度再加上本身的高度1. + return root == null ? 0 : 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); + + } +} + + + + + + + +``` diff --git "a/2018.12.07-leetcode104/\345\246\256\345\217\257.md" "b/2018.12.07-leetcode104/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..05236c02c --- /dev/null +++ "b/2018.12.07-leetcode104/\345\246\256\345\217\257.md" @@ -0,0 +1,70 @@ +```java +package sy181209; + + + +/** + * @author suyuan + * +给定一个二叉树,找出其最大深度。 + +二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 + +说明: 叶子节点是指没有子节点的节点。 + +示例: +给定二叉树 [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回它的最大深度 3 。 + + */ +public class leetcode_104二叉树的最大深度 +{ + + public static void main(String[] args) + { + TreeNode node1=new TreeNode(1); + TreeNode node2=new TreeNode(2); + TreeNode node3=new TreeNode(3); + TreeNode node4=new TreeNode(4); + TreeNode node5=new TreeNode(5); + + node1.left=node2; + node1.right=node3; + + node2.left=node4; + node2.right=node5; + + node3.left=null; + node3.right=null; + + node4.left=null; + node4.right=null; + node5.left=null; + node5.right=null; + + System.out.println(maxDepth(node1)); + + } + + public static int maxDepth(TreeNode root) + { + if(root==null) + return 0; + return Math.max(maxDepth(root.left), maxDepth(root.right))+1; + } + +} + + class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } +``` diff --git "a/2018.12.07-leetcode104/\345\274\240\345\260\217\350\203\226.md" "b/2018.12.07-leetcode104/\345\274\240\345\260\217\350\203\226.md" new file mode 100644 index 000000000..429d19710 --- /dev/null +++ "b/2018.12.07-leetcode104/\345\274\240\345\260\217\350\203\226.md" @@ -0,0 +1,19 @@ + /** + 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: + int maxDepth(TreeNode* root){ + if(root==nullptr) return 0; + int leftDepth=maxDepth(root->left); + int rightDepth=maxDepth(root->right); + if(leftDepth>rightDepth) return leftDepth+1; + else return rightDepth+1; + } + }; diff --git "a/2018.12.07-leetcode104/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.07-leetcode104/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..c12ae6681 --- /dev/null +++ "b/2018.12.07-leetcode104/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,68 @@ +### [104. Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/description/) +**题目描述** +> 二叉树的最大深度 + +**例子** +给定二叉树 [3,9,20,null,null,15,7], + 3 + / \ + 9 20 + / \ + 15 7 +返回它的最大深度 3 。 + +**思想** +(递归) +最大深度等于左右子树的最大深度加1。 +(非递归) +层次遍历 + +**解法1** +递归 +```python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def maxDepth(self, root): + """ + :type root: TreeNode + :rtype: int + """ + if not root: + return 0 + return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) +``` + +**解法2** +层次遍历 +```python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def maxDepth(self, root): + """ + :type root: TreeNode + :rtype: int + """ + depth = 0 + queue = [root] + while queue and root: + depth += 1 + for _ in range(len(queue)): + node = queue.pop(0) + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + return depth +``` \ No newline at end of file diff --git "a/2018.12.07-leetcode104/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.07-leetcode104/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..3b2dadf1b --- /dev/null +++ "b/2018.12.07-leetcode104/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,21 @@ +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + if(root==null){ + return 0; + } + int left = maxDepth(root.left); + int right = maxDepth(root.right); + return Math.max(left,right)+1; + } +} +``` diff --git "a/2018.12.07-leetcode104/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.07-leetcode104/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..8622d49a2 --- /dev/null +++ "b/2018.12.07-leetcode104/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,31 @@ +``` +/** + * 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: + int maxDepth(TreeNode* root) { + if(!root) return 0; + + int maxD = height(root, 0); + return maxD; + } + + int height(TreeNode *node, int h) + { + if(!node) return h; + + h++; + + int l = height(node->left, h); + int r = height(node->right, h); + return max(l, r); + } +}; +``` diff --git "a/2018.12.07-leetcode104/\350\216\216\350\216\216.md" "b/2018.12.07-leetcode104/\350\216\216\350\216\216.md" new file mode 100644 index 000000000..796faaae5 --- /dev/null +++ "b/2018.12.07-leetcode104/\350\216\216\350\216\216.md" @@ -0,0 +1,21 @@ +``` +class Solution: + def maxDepth(self, root): + """ + :type root: TreeNode + :rtype: int + """ + q = [root] + j = 0 + if not root: + return 0 + while q: + for i in range(len(q)): + temp = q.pop(0) + if temp.left: + q.append(temp.left) + if temp.right: + q.append(temp.right) + j += 1 + return j +``` diff --git "a/2018.12.07-leetcode104/\351\223\201\347\224\267\347\245\236sama.md" "b/2018.12.07-leetcode104/\351\223\201\347\224\267\347\245\236sama.md" new file mode 100644 index 000000000..cd5613039 --- /dev/null +++ "b/2018.12.07-leetcode104/\351\223\201\347\224\267\347\245\236sama.md" @@ -0,0 +1,76 @@ + + + + +## 104.二叉树最大深度 + +> [https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/) + +### 一、题目 + +给定一个二叉树,找出其最大深度。 + +二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 + +**说明:** 叶子节点是指没有子节点的节点。 + +**示例:**给定二叉树 `[3,9,20,null,null,15,7]`, + +``` + 3 + / \ + 9 20 + / \ + 15 7 +``` + +返回它的最大深度 3 。 + +### 二、思路 + +- 二叉树问题锁定递归 +- 最大深度=左子树最大深度,右子树最大深度,中的大的那个 +- 递归出口:root==null 返回0 + +### 三、题解 + +#### 递归解法 + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { int val; TreeNode + * left; TreeNode right; TreeNode(int x) { val = x; } } + */ +class Solution { + public int maxDepth(TreeNode root) { + if(root==null) return 0; + return Math.max(maxDepth(root.left),maxDepth(root.right))+1; + } +``` + +#### 非递归解法 + +```java +public int maxDepth(TreeNode root) { + if(root==null) return 0; + Queue q = new LinkedList<>(); + q.offer(root); + int level=1; + while(!q.isEmpty()){ + int size = q.size(); + while(size-->0){ + TreeNode popNow = q.poll(); + if(popNow.left!=null){ + q.offer(popNow.left); + } + if(popNow.right!=null){ + q.offer(popNow.right); + } + } + level++; + } + return level-1; + } +``` + diff --git "a/2018.12.07-leetcode104/\351\230\263.md" "b/2018.12.07-leetcode104/\351\230\263.md" new file mode 100644 index 000000000..eb448d66c --- /dev/null +++ "b/2018.12.07-leetcode104/\351\230\263.md" @@ -0,0 +1,17 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + if(root == null) { + return 0; + } + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); + } +} diff --git a/2018.12.08-leetcode105/-.md b/2018.12.08-leetcode105/-.md new file mode 100644 index 000000000..d9e59488a --- /dev/null +++ b/2018.12.08-leetcode105/-.md @@ -0,0 +1,35 @@ +public class Solution_105 { + public TreeNode buildTree(int[] preorder, int[] inorder) { + if (inorder.length == 0) { + return null; + } + TreeNode root = new TreeNode(preorder[0]); + if (inorder.length == 1) { + return root; + } + int index = 0; + for (int i = 1; i < inorder.length; i++) { + if (inorder[i] == preorder[0]) { + index = i + 1; + break; + } + } + int[] letfArr = null; + int[] rightArr = null; + if (index != 0) { + letfArr = Arrays.copyOfRange(inorder, 0, index); + rightArr = Arrays.copyOfRange(inorder, index, inorder.length); + } + + root.left = buildTree(Arrays.copyOfRange(preorder, 1, preorder.length), letfArr); + index -= 2; + for (int i = 0; i < preorder.length; i++) { + if (preorder[i] == inorder[index]) { + index = i; + break; + } + } + root.right = buildTree(Arrays.copyOfRange(preorder,index+1,preorder.length),rightArr); + return root; + } +} diff --git "a/2018.12.08-leetcode105/105. \344\273\216\345\211\215\345\272\217\344\270\216\344\270\255\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227\346\236\204\351\200\240\344\272\214\345\217\211\346\240\221.md" "b/2018.12.08-leetcode105/105. \344\273\216\345\211\215\345\272\217\344\270\216\344\270\255\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227\346\236\204\351\200\240\344\272\214\345\217\211\346\240\221.md" new file mode 100644 index 000000000..471eee665 --- /dev/null +++ "b/2018.12.08-leetcode105/105. \344\273\216\345\211\215\345\272\217\344\270\216\344\270\255\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227\346\236\204\351\200\240\344\272\214\345\217\211\346\240\221.md" @@ -0,0 +1,17 @@ + +根据一棵树的前序遍历与中序遍历构造二叉树。 + +注意: +你可以假设树中没有重复的元素。 + +例如,给出 + +前序遍历 preorder = [3,9,20,15,7] +中序遍历 inorder = [9,3,15,20,7] +返回如下的二叉树: + + 3 + / \ + 9 20 + / \ + 15 7 diff --git a/2018.12.08-leetcode105/Avalon.md b/2018.12.08-leetcode105/Avalon.md new file mode 100644 index 000000000..63bd831f4 --- /dev/null +++ b/2018.12.08-leetcode105/Avalon.md @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + TreeNode root = reConstructBinaryTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); + return root; + } + + + public static TreeNode reConstructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn){ + if (startPre > endPre || startIn > endIn) { + return null; + } + TreeNode root = new TreeNode(pre[startPre]); + for (int i = startIn; i <= endIn; i++) + if (in[i] == pre[startPre]) { + root.left = reConstructBinaryTree(pre, startPre + 1, startPre + i - startIn, in, startIn, i - 1); + root.right = reConstructBinaryTree(pre, i - startIn + startPre + 1, endPre, in, i + 1, endIn); + break; + } + return root; + + } +} diff --git a/2018.12.08-leetcode105/Be a fresh man.md b/2018.12.08-leetcode105/Be a fresh man.md new file mode 100644 index 000000000..0f41fb296 --- /dev/null +++ b/2018.12.08-leetcode105/Be a fresh man.md @@ -0,0 +1,71 @@ +## 105_(从前序与后序遍历序列构造二叉树)Construct Binary Tree from Preorder and Inorder Traversal +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +根据一棵树的前序遍历与中序遍历构造二叉树。
+__注意__: +你可以假设树中没有重复的元素。 +### 1.2 输入与输出 +输入: +* vector& preorder:前序遍历的序列的引用 +* vector& inorder:中序遍历的序列的引用 + +输出: +* TreeNode*:构造的二叉树的根节点 +### 1.3 样例 +#### 1.3.1 样例1 +输入:前序遍历 preorder = [3,9,20,15,7],中序遍历 inorder = [9,3,15,20,7]
+输出: + + 3 + / \ + 9 20 + / \ + 15 7 +## 2 思路描述与代码 +### 2.1 思路描述(递归法) +最常见的构造树的方法就是递归了。二叉树的前序遍历的第一个节点肯定是根节点,该节点在中序遍历中是个分节点,在分节点左边的节点是左子树的所有节点,右边是右子树的所有节点。利用该思路构造二叉树。 +```cpp +TreeNode* buildTree_recurse(preorder_begin, preorder_len, inorder_begin, inorder_len){ + 若前序遍历长度为 0 ,返回空指针; + 构建根节点 root, 值为 *preorder_begin ; + 找到 *preorder_begin 在中序遍历中的位置 idx; + //递归左右子树 + root->left = buildTree_recurse(preorder_begin + 1, idx, inorder_begin, idx); + root->right = buildTree_recurse(preorder_begin + idx + 1, preorder_len - idx - 1, inorder_begin + i + 1, inorder_len - idx - 1); + 返回 root; +} +``` + +### 2.2 代码 +```cpp +typedef vector::iterator iter; +TreeNode* buildTree(vector& preorder, vector& inorder) { + return buildTree_recurse(preorder.begin(), preorder.size(), inorder.begin(), inorder.size()); +} +TreeNode* buildTree_recurse(iter preorder_begin, int preorder_len, iter inorder_begin, int inorder_len){ + if(preorder_len == 0) return nullptr; + TreeNode* root = new TreeNode(*preorder_begin); + int i; + for( i = 0; i < inorder_len; i++ ){ + if(*(inorder_begin + i) == *preorder_begin) break; + } + root->left = buildTree_recurse(preorder_begin + 1, i, inorder_begin, i); + root->right = buildTree_recurse(preorder_begin + i + 1, preorder_len - i - 1, inorder_begin + i + 1, inorder_len - i - 1); + return root; +} +``` + +## 3 思考与拓展 +### 3.1 思考 +本题主要利用二叉树前序和中序遍历的特点递归构造二叉树,该思路也能应用在由后序和中序构造二叉树。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +递归法|O(n)|O(n) +#### 3.1.3 难点分析 +1. 需要考虑边界条件即遍历长度为 0 的时候 +2. 找到递归的表达式 +### 3.2 拓展 +如果让你从中序遍历和后序遍历构造二叉树呢? diff --git a/2018.12.08-leetcode105/Despacito.md b/2018.12.08-leetcode105/Despacito.md new file mode 100644 index 000000000..61c83bb70 --- /dev/null +++ b/2018.12.08-leetcode105/Despacito.md @@ -0,0 +1,46 @@ +# LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal +## 1. Description +Given preorder and inorder traversal of a tree, construct the binary tree. + +Note: +You may assume that duplicates do not exist in the tree. + +For example, given + +preorder = [3,9,20,15,7] + +inorder = [9,3,15,20,7] + +Return the following binary tree: + + 3 + / \ + 9 20 + / \ + 15 7 + +## 2. Solution +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def buildTree(self, preorder, inorder): + """ + :type preorder: List[int] + :type inorder: List[int] + :rtype: TreeNode + """ + if len(preorder) == 0: + return None + if len(preorder) == 1: + return TreeNode(preorder.pop(0)) + root = TreeNode(preorder.pop(0)) + root.left = self.buildTree(preorder[:inorder.index(root.val)], inorder[:inorder.index(root.val)]) + root.right = self.buildTree(preorder[inorder.index(root.val):], inorder[inorder.index(root.val)+1:]) + return root +``` \ No newline at end of file diff --git a/2018.12.08-leetcode105/GatesMa.md b/2018.12.08-leetcode105/GatesMa.md new file mode 100644 index 000000000..24943fd92 --- /dev/null +++ b/2018.12.08-leetcode105/GatesMa.md @@ -0,0 +1,40 @@ +# c++ +```cpp +/** + * 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* buildTree(vector& preorder, vector& inorder) { + return buildTree(preorder, inorder, 0, preorder.size()-1, 0, inorder.size()-1); + } + + /**重载这个函数*/ + //表示 前序为preorder,从下标p_l到p_r,中序为inorder,下标从i_l到i_r构建 树 + TreeNode* buildTree(vector& preorder, vector inorder, int p_l, int p_r, int i_l, int i_r) { + if(p_l > p_r) return NULL; + if(p_l == p_r) return new TreeNode(preorder[p_l]); + int index = find(inorder, i_l, i_r, preorder[p_l]);//根节点在中序遍历中的位置 + TreeNode* node = new TreeNode(preorder[p_l]); + int pre_left_len = index - i_l;//左子树的长度 + // preorder[p_lo+1 ... p_lo+pre_left_len]是先序数组中与现结点左子树对应的部分。 + // inorder[i_lo ... index_in-1]是中序数组中与现结点左子树对应的部分。 + node->left = buildTree(preorder, inorder, p_l+1, p_l+pre_left_len, i_l, index - 1); + node->right = buildTree(preorder, inorder, p_l+pre_left_len+1, p_r, index+1, i_r); + return node; + } + + int find(vector& inorder, int l, int r, int node_val) { + for(int i =l;i <= r;i++){ + if(inorder[i] == node_val) return i; + } + return -1; + } +}; +``` diff --git a/2018.12.08-leetcode105/Istoryforever.md b/2018.12.08-leetcode105/Istoryforever.md new file mode 100644 index 000000000..9ab02927f --- /dev/null +++ b/2018.12.08-leetcode105/Istoryforever.md @@ -0,0 +1,38 @@ +leetcode of 105 +``` +/** + * 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* buildTree(vector& preorder, vector& inorder,int s,int t,int &i) { + if(i == preorder.size()) return nullptr; + int val = preorder[i++]; + TreeNode * root = new TreeNode(val); + if(s >= t - 1){ + return root; + } + int index = find(inorder.begin()+s,inorder.begin()+t,val) - inorder.begin(); + if(index != s){ + root->left = buildTree(preorder,inorder,s,index,i); + } + if(index != t - 1){ + root->right = buildTree(preorder,inorder,index+1,t,i); + } + return root; + + + } + TreeNode* buildTree(vector& preorder, vector& inorder){ + int i=0; + return buildTree(preorder,inorder,0,preorder.size(),i); + } +}; +``` diff --git a/2018.12.08-leetcode105/MQQM.cpp b/2018.12.08-leetcode105/MQQM.cpp new file mode 100644 index 000000000..ee0c8999c --- /dev/null +++ b/2018.12.08-leetcode105/MQQM.cpp @@ -0,0 +1,46 @@ +/* + 题目: + 根据一棵树的前序遍历与中序遍历构造二叉树。 + + 参考: + https://blog.csdn.net/u014265347/article/details/76400062 +*/ + +/** + * 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* buildTree(vector& preorder, vector& inorder) { + int l1 = 0; + int l2 = 0; + int r1 = preorder.size() - 1; + int r2 = inorder.size() - 1; + return build(preorder, inorder, l1, r1, l2, r2); + } + TreeNode* build(vector& preorder, vector& inorder, int l1, int r1, int l2, int r2){ + if (l1 > r1){//中序遍历中,根前面没有元素,那么l1>r1 + return NULL; + } + + int root_val = preorder[l1];//中序遍历中根的索引 + TreeNode* root = new TreeNode(root_val); + + int idx;//确定根在中序遍历中的索引 + for (idx = l2; idx <= r2; idx++){ + if (inorder[idx] == root_val){ + break; + } + } + root->left = build(preorder, inorder, l1 + 1, l1 + (idx - l2), l2, idx - 1); + root->right = build(preorder, inorder, l1 + idx - l2 + 1, r1, idx + 1, r2); + + return root; + } +}; diff --git a/2018.12.08-leetcode105/Ostrichcrab.md b/2018.12.08-leetcode105/Ostrichcrab.md new file mode 100644 index 000000000..8feeff067 --- /dev/null +++ b/2018.12.08-leetcode105/Ostrichcrab.md @@ -0,0 +1,25 @@ +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode buildTreeHelper(int[] inorder, int is, int ie, int[] preorder, int ps){ + if(is>ie || ps>=preorder.length) return null; + TreeNode root = new TreeNode(preorder[ps]); + int rootAtIn = is; + while(inorder[rootAtIn] != root.val) rootAtIn++; + root.left = buildTreeHelper(inorder,is,rootAtIn-1,preorder,ps+1); + root.right = buildTreeHelper(inorder,rootAtIn+1,ie,preorder,ps+rootAtIn-is+1); + return root; + } + public TreeNode buildTree(int[] preorder, int[] inorder) { + return buildTreeHelper(inorder,0,inorder.length-1,preorder,0); + } +} +``` diff --git a/2018.12.08-leetcode105/Sagittarius.md b/2018.12.08-leetcode105/Sagittarius.md new file mode 100644 index 000000000..a98b74af6 --- /dev/null +++ b/2018.12.08-leetcode105/Sagittarius.md @@ -0,0 +1,38 @@ +``` +/** + * 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* buildTree(vector& preorder, vector& inorder) { + return rebuildTree(0,preorder.size()-1,0,inorder.size()-1,preorder,inorder); + } + + TreeNode* rebuildTree(int preL,int preR,int inL,int inR,vector& preorder,vector& inorder) + { + if(preL>preR) + return nullptr; + TreeNode* root=new TreeNode(preorder[preL]); + int k; + for(int i=0;i<=inR;i++) + { + if(preorder[preL]==inorder[i]) + { + k=i; + break; + } + } + int numPre=k-inL; + root->left=rebuildTree(preL+1,preL+numPre,inL,k-1,preorder,inorder); + root->right=rebuildTree(preL+numPre+1,preR,inL+numPre+1,inR,preorder,inorder); + + return root; + } +}; +``` diff --git a/2018.12.08-leetcode105/Sunny.md b/2018.12.08-leetcode105/Sunny.md new file mode 100644 index 000000000..13fe0dcc5 --- /dev/null +++ b/2018.12.08-leetcode105/Sunny.md @@ -0,0 +1,30 @@ +```java +class Solution { + + private int i = 0; + + public TreeNode buildTree(int[] preorder, int[] inorder) { + if (preorder == null || preorder.length == 0) + return null; + int val = preorder[i]; + int index = inorder.length - 1; + for (; index >= 0; index--) { + if (inorder[index] == val) { + break; + } + } + if (index >= 0) { + TreeNode node = new TreeNode(val); + i++; + if (inorder.length > 1 && i < preorder.length) { + node.left = buildTree(preorder, Arrays.copyOfRange(inorder, 0, index)); + if (i < preorder.length) { + node.right = buildTree(preorder, Arrays.copyOfRange(inorder, index+1, inorder.length)); + } + } + return node; + } + return null; + } +} +``` diff --git a/2018.12.08-leetcode105/TheRocket.md b/2018.12.08-leetcode105/TheRocket.md new file mode 100644 index 000000000..36c00231e --- /dev/null +++ b/2018.12.08-leetcode105/TheRocket.md @@ -0,0 +1,32 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + Map map = new HashMap<>(); + for (int i = 0; i < inorder.length; ++i) { + map.put(inorder[i], i); + } + return buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map); + } + + private TreeNode buildTree(int[] preorder, int preBegin, int preEnd, int[] inorder, int inBegin, int inEnd, Map map) { + if (preBegin > preEnd || inBegin > inEnd) { + return null; + } + TreeNode root = new TreeNode(preorder[preBegin]); + int i = map.get(root.val); + int leftEnd = preBegin + i - inBegin; + root.left = buildTree(preorder, preBegin + 1, leftEnd, inorder, inBegin, i - 1, map); + root.right = buildTree(preorder, leftEnd + 1, preEnd, inorder, i + 1, inEnd, map); + return root; + } +} +``` diff --git a/2018.12.08-leetcode105/Typing.txt b/2018.12.08-leetcode105/Typing.txt new file mode 100644 index 000000000..a9bf9c26b --- /dev/null +++ b/2018.12.08-leetcode105/Typing.txt @@ -0,0 +1,63 @@ +public class Main105 { + + public static void main(String[] args){ + Main105 main = new Main105(); + main.test(); + } + + public void test(){ + TreeNode treeNode = buildTree(new int[]{3,9,20,15,7},new int[]{9,3,15,20,7}); + System.out.println(treeNode); + } + + public TreeNode buildTree(int[] preorder, int[] inorder) { + int pLen = preorder.length; + int iLen = inorder.length; + if(pLen==0 && iLen==0){ + return null; + } + + Map inMap = new HashMap<>(); + for (int i = 0;i inMap) + { + //建立根节点 + TreeNode tree = new TreeNode(preOrder[pStart]); + tree.left = null; + tree.right = null; + if(pStart == pEnd && iStart == iEnd) + { + return tree; + } + int root = inMap.getOrDefault(preOrder[pStart],0); + //找中序遍历中的根节点 + //划分左右子树 + int leftLength = root - iStart;//左子树 + int rightLength = iEnd - root;//右子树 + //遍历左子树 + if(leftLength>0) + { + tree.left = buildNode(preOrder,pStart+1, pStart+leftLength, iStart, root-1, inMap); + } + //遍历右子树 + if(rightLength>0) + { + tree.right = buildNode(preOrder,pStart+leftLength+1, pEnd, root+1, iEnd,inMap); + } + return tree; + } + + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } +} diff --git a/2018.12.08-leetcode105/WhiteNight.md b/2018.12.08-leetcode105/WhiteNight.md new file mode 100644 index 000000000..84ec8e52a --- /dev/null +++ b/2018.12.08-leetcode105/WhiteNight.md @@ -0,0 +1,64 @@ +```java +public class Tree16 { + public static class TreeNode { + int data; + TreeNode left; + TreeNode right; + + TreeNode(int val) { + data = val; + } + } + + public TreeNode buildTree(int[] preorder, int[] inorder) { + if (preorder == null || inorder == null || preorder.length == 0) + return null; + return buildCore(preorder, 0,preorder.length - 1,inorder, 0, inorder.length - 1); + } + + private TreeNode buildCore(int[] preorder, int preSt, int preEnd, int[] inorder, int inSt, int inEnd){ + int rootValue = preorder[preSt]; + TreeNode root = new TreeNode(rootValue); + + if (preSt == preEnd) + return root; + + int rootInorder = inSt; + while (inorder[rootInorder] != rootValue && rootInorder <= inEnd) + rootInorder++; + + int leftLength = rootInorder - inSt; //左子树的长度 + int leftPreEnd = preSt + leftLength; //前序序列中左子树的最后一个节点 + + // 左子树非空 + if (leftLength > 0){ + root.left = buildCore(preorder,preSt+1, leftPreEnd, inorder, inSt, rootInorder-1); + } + + // 右子树非空 + // preEnd 和preSt是前序数组的结尾和开头,相减就是长度,如果左子树长度小于整个长度,那么说明右子树肯定存在。 + // 那么对右子树也进行同样的构建树的操作。 + if (leftLength < preEnd - preSt){ + root.right = buildCore(preorder, leftPreEnd+1, preEnd, inorder, rootInorder+1, inEnd); + } + + return root; + } + + private void inOrder(TreeNode root){ + if (root != null){ + inOrder(root.left); + System.out.print(root.data + " "); + inOrder(root.right); + } + } + + public static void main(String[] args) { + Tree16 t = new Tree16(); + int[] preorder = {3, 9, 20, 15, 7}; + int[] inorder = {9, 3, 15, 20, 7}; + TreeNode resTree = t.buildTree(preorder, inorder); + t.inOrder(resTree); + } +} +``` \ No newline at end of file diff --git a/2018.12.08-leetcode105/fish.md b/2018.12.08-leetcode105/fish.md new file mode 100644 index 000000000..c33fe1152 --- /dev/null +++ b/2018.12.08-leetcode105/fish.md @@ -0,0 +1,60 @@ +``` +public class Solution { + public static TreeNode binaryTree(TreeNode node, List preOrder, List inOrder) { + if (!preOrder.isEmpty()) { + Integer val = preOrder.get(0); + int preIndex = preOrder.indexOf(val); + int inIndex = inOrder.indexOf(val); + List plOrder = preOrder.subList(preIndex + 1, inIndex + 1); + List prOrder = preOrder.subList(inIndex + 1, preOrder.size()); + + List ilOrder = inOrder.subList(0, inIndex); + List irOrder = inOrder.subList(inIndex + 1, inOrder.size()); + if (node == null) { + node = new TreeNode(val, null, null); + } + TreeNode lnode = null,rnode = null; + if (!plOrder.isEmpty()){ + lnode = new TreeNode(plOrder.get(0), null, null); + } + if (!prOrder.isEmpty()) { + rnode = new TreeNode(prOrder.get(0), null, null); + } + node.setLeft(lnode); + node.setRight(rnode); + binaryTree(lnode, plOrder, ilOrder); + binaryTree(rnode, prOrder, irOrder); + } + return node; + } + + public static void main(String[] args) { + List preOrder = new ArrayList<>(); + preOrder.add(1); + preOrder.add(4); + preOrder.add(6); + preOrder.add(8); + preOrder.add(9); + preOrder.add(10); + preOrder.add(11); + List inOrder = new ArrayList<>(); + inOrder.add(6); + inOrder.add(4); + inOrder.add(1); + inOrder.add(9); + inOrder.add(8); + inOrder.add(10); + inOrder.add(11); + System.out.println(binaryTree(null, preOrder, inOrder)); + } +} + +@Data +@AllArgsConstructor +@NoArgsConstructor +@ToString +class TreeNode { + private int val; + private TreeNode left; + private TreeNode right; +} \ No newline at end of file diff --git a/2018.12.08-leetcode105/sourcema.md b/2018.12.08-leetcode105/sourcema.md new file mode 100644 index 000000000..78760d353 --- /dev/null +++ b/2018.12.08-leetcode105/sourcema.md @@ -0,0 +1,41 @@ +# LeetCode 105 + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + + TreeNode node=preInArrGenerateTree(preorder,inorder,0,preorder.length-1,0,inorder.length-1); + return node; + } + public TreeNode preInArrGenerateTree(int[] preArr,int[] inArr,int preStart,int preEnd, + int inStart,int inEnd) { + if (preStart>preEnd) { + return null; + } + TreeNode head = new TreeNode(preArr[preStart]); + int index = findHeadInArr(inArr, inStart, inEnd,preArr[preStart]); + head.left = preInArrGenerateTree(preArr, inArr, preStart + 1, preStart+index-inStart, inStart, index - 1); + head.right = preInArrGenerateTree(preArr, inArr, preStart+index-inStart+1, preEnd, index+1, inEnd); + return head; + } + + public int findHeadInArr(int[] inArr, int inStart, int inEnd,int target) { + int index=0; + for (int i = inStart; i <=inEnd; i++) { + if (inArr[i] == target) { + index=i; + break; + } + + } + return index; + + } + } diff --git a/2018.12.08-leetcode105/syuan.md b/2018.12.08-leetcode105/syuan.md new file mode 100644 index 000000000..527b036cc --- /dev/null +++ b/2018.12.08-leetcode105/syuan.md @@ -0,0 +1,31 @@ +##### 代码 + +``` +class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + TreeNode root=reConstructBinaryTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1); + return root; + } + //前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6} + private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) { + + if(startPre>endPre||startIn>endIn) + return null; + TreeNode root=new TreeNode(pre[startPre]); + + for(int i=startIn;i<=endIn;i++) + if(in[i]==pre[startPre]){ + root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1); + root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn); + } + + return root; + } +} +``` +> root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1); +> startPre+1 pre中下一个为左子树的根结点 startPre+i-startIn中i-startIn为左结点的个数 +in中 i-1全为左结点 + +> root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn); +> diff --git a/2018.12.08-leetcode105/zjukk.md b/2018.12.08-leetcode105/zjukk.md new file mode 100644 index 000000000..d104071d0 --- /dev/null +++ b/2018.12.08-leetcode105/zjukk.md @@ -0,0 +1,20 @@ +``` +class Solution { +public: + TreeNode* buildTree(vector& preorder, vector& inorder) { + return buildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1); + } + TreeNode* buildTree(vector& preorder, int pLeft, int pRight, vector& inorder, int iLeft, int iRight) { + if (pLeft > pRight) return NULL; + int i; + TreeNode* root = new TreeNode(preorder[pLeft]); + for (i = iLeft; i <= iRight; ++i) { + if (inorder[i] == root->val) break; + } + //i-iLeft == size(left) + root->left = buildTree(preorder, pLeft+1, pLeft-iLeft+i, inorder, iLeft, i-1); + root->right = buildTree(preorder, pLeft-iLeft+i+1, pRight, inorder, i+1, iRight); + return root; + } +}; +``` diff --git "a/2018.12.08-leetcode105/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" "b/2018.12.08-leetcode105/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" new file mode 100644 index 000000000..8cf63b15d --- /dev/null +++ "b/2018.12.08-leetcode105/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + return buildTree(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1); + } + private TreeNode buildTree(int[] preorder, int i, int j, int[] inorder, int k, int l) { + assert((j - i) == (l - k)); + if(i > j && k > l) return null; + if(i == j && k == l) return new TreeNode(preorder[i]); + int root = preorder[i]; + TreeNode res = new TreeNode(root); + int index = indexOfArray(inorder, k, l, root); //抛异常 + if(index == k) { //左子树为空 + res.val = inorder[index]; + res.left = null; + res. right = buildTree(preorder, i+1, j, inorder, k+1, l); + } + else if(index == l) { //右子树为空 + res.val = inorder[index]; + res.left = buildTree(preorder, i+1, j, inorder, k, l-1); + res.right = null; + } + else { + res.val = inorder[index]; + res.left = buildTree(preorder, i+1, i+(index-k), inorder, k, index-1); + res.right = buildTree(preorder, i+(index-k)+1, j, inorder, index+1, l); + } + return res; + } + private int indexOfArray(int[] array, int begin, int end, int value) { + for(int i = begin; i <= end; i++){ + if(array[i] == value) + return i; + } + return -1; + } +} diff --git "a/2018.12.08-leetcode105/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.08-leetcode105/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..637be74e3 --- /dev/null +++ "b/2018.12.08-leetcode105/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,31 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + TreeNode biuld(int[] pre,int pl,int pr,int[] in,int il,int ir){ + if(pl>pr||il>ir||pl<0||il<0)return null; + TreeNode root = new TreeNode(pre[pl]); + if(pl==pr||il==ir)return root; + int in_p=-1; + for(int i=il;i<=ir;i++){ + if(in[i]==pre[pl]){ + in_p=i;break; + } + } + int num=in_p-il; + root.left = biuld(pre,pl+1,pl+num,in,il,in_p-1); + root.right= biuld(pre,pl+num+1,pr,in,in_p+1,ir); + return root; + } + public TreeNode buildTree(int[] preorder, int[] inorder) { + return biuld(preorder,0,preorder.length-1,inorder,0,inorder.length-1); + } +} +``` diff --git "a/2018.12.08-leetcode105/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.12.08-leetcode105/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..c222fe9d5 --- /dev/null +++ "b/2018.12.08-leetcode105/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,51 @@ +``` +/** + 根据一棵树的前序遍历与中序遍历构造二叉树。 + +注意: +你可以假设树中没有重复的元素。 + +例如,给出 + +前序遍历 preorder = [3,9,20,15,7] +中序遍历 inorder = [9,3,15,20,7] +返回如下的二叉树: + + 3 + / \ + 9 20 + / \ + 15 7 + * + 转载原文:https://blog.csdn.net/zd836614437/article/details/54237349 + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + int size = preorder.length; + if(size == 0) + return null; + return help(preorder, inorder, 0, size - 1, 0, size - 1); + } + public TreeNode help(int[] preorder, int[] inorder, int pleft, int pright, int ileft, int iright) { + if(pleft > pright || ileft > iright) + return null; + TreeNode root = new TreeNode(preorder[pleft]); + int i;//这里需要记录根的位置 + for(i = ileft; i <= iright; i++){//已知先序遍历的根,在中序遍历中找到相应的根节点的位置 + if(inorder[i] == preorder[pleft]) + break; + } + //构建左子树,pleft+1,pleft+(i-ileft)。代表先序遍历中左子树的值范围,(i-ileft)其中代表中序中走过相应的长度,ileft, i - 1 代表中序遍历中左子树 的值范围。 + root.left = help(preorder, inorder,pleft + 1, pleft + i - ileft, ileft, i - 1); + root.right = help(preorder, inorder,pleft + i - ileft + 1, pright, i + 1, iright); + return root; + } +} +``` diff --git "a/2018.12.08-leetcode105/\345\246\256\345\217\257.md" "b/2018.12.08-leetcode105/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..a2bc248f0 --- /dev/null +++ "b/2018.12.08-leetcode105/\345\246\256\345\217\257.md" @@ -0,0 +1,85 @@ +```java +package sy181209; + +import java.util.HashMap; + + + +/** + * @author suyuan + * +根据一棵树的前序遍历与中序遍历构造二叉树。 + +注意: +你可以假设树中没有重复的元素。 + +例如,给出 + +前序遍历 preorder = [3,9,20,15,7] +中序遍历 inorder = [9,3,15,20,7] +返回如下的二叉树: + + 3 + / \ + 9 20 + / \ + 15 7 + + */ +public class leetcode_105从前序与中序遍历序列构造二叉树 +{ + + public static void main(String[] args) + { + int[]preorder = new int[] {3,9,2,8,5,20,15,6,7}; + int[] inorder = new int[] {8,2,9,5,3,6,15,20,7}; + TreeNode node=buildTree(preorder, inorder); + print(node); + + } + + public static TreeNode buildTree(int[] preorder, int[] inorder) + { + if(preorder==null || inorder==null) + return null; + HashMap map=new HashMap(); + //由于之后查找很频繁,把值存在哈希表里.查找快 + for(int i=0;i map) + { + if(pi>pj) + return null; + TreeNode head=new TreeNode(p[pi]); + int index=map.get(p[pi]); + //根是先序的第一个点 + //index中序节点前有的节点 + head.left=preIn(p, pi+1, pi+index-ni, n, ni, index-1, map); + head.right=preIn(p, pi+index-ni+1, pj, n, index+1, nj, map); + return head; + } + + private static void print(TreeNode tree, int key, int direction) { + + if(tree != null) { + + if(direction==0) // tree是根节点 + System.out.printf("%2d is root\n", tree.val); + else // tree是分支节点 + System.out.printf("%2d is %2d's %6s child\n",tree.val,key, direction==1?"right" : "left"); + + print(tree.left, tree.val, -1); + print(tree.right,tree.val, 1); + } + } + + public static void print(TreeNode node) + { + if (node != null) + print(node, node.val, 0); + } +} +``` diff --git "a/2018.12.08-leetcode105/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.08-leetcode105/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..9e3bfa570 --- /dev/null +++ "b/2018.12.08-leetcode105/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,48 @@ +### [105. Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/) + +**题目描述** +> 给定前序和中序遍历,重构二叉树。 + +> 假设树中没有重复结点。 + +**例子** +前序遍历 preorder = [3,9,20,15,7] +中序遍历 inorder = [9,3,15,20,7] +返回如下的二叉树: + + 3 + / \ + 9 20 + / \ + 15 7 + +**思想** +前序 - 根左右;中序 - 左右根 +(递归) + +**解法** +```python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def buildTree(self, preorder, inorder): + """ + :type preorder: List[int] + :type inorder: List[int] + :rtype: TreeNode + """ + if not preorder: + return None + root = TreeNode(preorder[0]) + idx = inorder.index(preorder[0]) + + root.left = self.buildTree(preorder[1:idx+1], inorder[:idx]) + root.right = self.buildTree(preorder[idx+1:], inorder[idx+1:]) + + return root +``` \ No newline at end of file diff --git "a/2018.12.08-leetcode105/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.08-leetcode105/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..9ca80978d --- /dev/null +++ "b/2018.12.08-leetcode105/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,34 @@ +``` +/** + * 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* buildTree(vector& preorder, vector& inorder) { + + return buildT(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1); + } + + TreeNode *buildT(vector& preorder, int pLeft, int pRight, vector& inorder, int iLeft, int iRight) + { + if(pLeft>pRight || iLeft>iRight) return NULL; + + TreeNode *root = new TreeNode(preorder[pLeft]); + int i; + for(i=iLeft; i<=iRight; i++) + { + if(inorder[i] == preorder[pLeft]) break; + } + + root->left = buildT(preorder, pLeft+1, pLeft+i-iLeft, inorder, iLeft, i-1); + root->right = buildT(preorder, pLeft+i-iLeft+1, pRight, inorder, i+1, iRight); + return root; + } +}; +``` diff --git "a/2018.12.08-leetcode105/\350\216\216\350\216\216.md" "b/2018.12.08-leetcode105/\350\216\216\350\216\216.md" new file mode 100644 index 000000000..e361e3ab0 --- /dev/null +++ "b/2018.12.08-leetcode105/\350\216\216\350\216\216.md" @@ -0,0 +1,16 @@ +``` +class Solution: + def buildTree(self, preorder, inorder): + """ + :type preorder: List[int] + :type inorder: List[int] + :rtype: TreeNode + """ + if not preorder: + return None + root = TreeNode(preorder[0]) + n = inorder.index(root.val) + root.left = self.buildTree(preorder[1:n+1],inorder[:n]) + root.right = self.buildTree(preorder[n+1:],inorder[n+1:]) + return root +``` diff --git "a/2018.12.08-leetcode105/\351\230\263.md" "b/2018.12.08-leetcode105/\351\230\263.md" new file mode 100644 index 000000000..9aaafecf9 --- /dev/null +++ "b/2018.12.08-leetcode105/\351\230\263.md" @@ -0,0 +1,30 @@ +class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + int preLength = preorder.length; + int inLength = inorder.length; + return buildTree(preorder, 0, preLength-1, inorder, 0, inLength-1); + } + + public TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) { + if(preStart > preEnd||inStart > inEnd) { + return null; + } + int rootVal = preorder[preStart]; + int rootIndex = 0; + //在中序遍历序列中找到根节点的值 + for(int i = inStart; i <= inEnd; i++) { + if(rootVal == inorder[i]) { + rootIndex = i; + break; + } + } + TreeNode root = new TreeNode(rootVal); + //找到左子树的长度 + int len = rootIndex - inStart; + //将先序序列和中序序列分别分割为左子树的部分,继续调用 + root.left = buildTree(preorder, preStart+1, preStart+len, inorder, inStart, rootIndex-1); + //将先序序列和中序序列分别分割为右子树的部分,继续调用 + root.right = buildTree(preorder, preStart+len+1, preEnd, inorder, rootIndex+1, inEnd); + return root; + } +} diff --git a/2018.12.09-leetcode106/-.md b/2018.12.09-leetcode106/-.md new file mode 100644 index 000000000..71951ef29 --- /dev/null +++ b/2018.12.09-leetcode106/-.md @@ -0,0 +1,26 @@ +public class Solution_106 { + public TreeNode buildTree(int[] inorder, int[] postorder) { + return helper(postorder.length - 1, 0, inorder.length - 1, inorder, postorder); + } + + public TreeNode helper(int index, int start, int end, int[] inorder, int[] postorder) { + if (start > end || index < 0 || index > postorder.length - 1) + return null; + TreeNode root = new TreeNode(postorder[index]); + int ino = -1; + for (int i = start; i <= end; i++) { + if (inorder[i] == postorder[index]) { + ino = i; + break; + } + } + if (ino != -1) { + root.right = helper(index - 1, start, ino - 1, inorder, postorder); + root.left = helper(index + 1, ino + 1, end, inorder, postorder); + } + + + return root; + } + +} diff --git "a/2018.12.09-leetcode106/106. \344\273\216\344\270\255\345\272\217\344\270\216\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227\346\236\204\351\200\240\344\272\214\345\217\211\346\240\221.md" "b/2018.12.09-leetcode106/106. \344\273\216\344\270\255\345\272\217\344\270\216\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227\346\236\204\351\200\240\344\272\214\345\217\211\346\240\221.md" new file mode 100644 index 000000000..65c705caf --- /dev/null +++ "b/2018.12.09-leetcode106/106. \344\273\216\344\270\255\345\272\217\344\270\216\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227\346\236\204\351\200\240\344\272\214\345\217\211\346\240\221.md" @@ -0,0 +1,17 @@ + +根据一棵树的中序遍历与后序遍历构造二叉树。 + +注意: +你可以假设树中没有重复的元素。 + +例如,给出 + +中序遍历 inorder = [9,3,15,20,7] +后序遍历 postorder = [9,15,7,20,3] +返回如下的二叉树: + + 3 + / \ + 9 20 + / \ + 15 7 diff --git a/2018.12.09-leetcode106/Avalon.md b/2018.12.09-leetcode106/Avalon.md new file mode 100644 index 000000000..3a9aeb6d0 --- /dev/null +++ b/2018.12.09-leetcode106/Avalon.md @@ -0,0 +1,31 @@ +public int postIndex = 0; + + /** + * @param inorder 中序遍历 + * @param postorder 后序遍历 + * @return + */ + public TreeNode buildTree(int[] inorder, int[] postorder) { + if (inorder.length == 0) + return null; + postIndex = postorder.length - 1; + return buildTree(inorder, postorder, postIndex, 0, inorder.length - 1); + } + + public static TreeNode buildTree(int[] inorder, int[] postorder, int postIndex, int start, int end) { + if (start > end) + return null; + if (start == end) + return new TreeNode(inorder[start]); + int index = start; + for (int i = start; i <= end; i++) { + if (inorder[i] == postorder[postIndex]) { + index = i; + break; + } + } + TreeNode root = new TreeNode(inorder[index]); + root.right = buildTree(inorder, postorder, postIndex - 1, index + 1, end); + root.left = buildTree(inorder, postorder, postIndex - (end - index) - 1, start, index - 1); + return root; + } diff --git a/2018.12.09-leetcode106/Be a fresh man.md b/2018.12.09-leetcode106/Be a fresh man.md new file mode 100644 index 000000000..da38ae11d --- /dev/null +++ b/2018.12.09-leetcode106/Be a fresh man.md @@ -0,0 +1,71 @@ +## 106_(从中序与后序遍历序列构造二叉树)Construct Binary Tree from Inorder and Postorder Traversal +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +根据一棵树的中序遍历与后序遍历构造二叉树。
+__注意__: +你可以假设树中没有重复的元素。 +### 1.2 输入与输出 +输入: +* vector& inorder:中序遍历的序列的引用 +* vector& postorder:后序遍历的序列的引用 + +输出: +* TreeNode*:构造的二叉树的根节点 +### 1.3 样例 +#### 1.3.1 样例1 +输入:中序遍历 inorder = [9,3,15,20,7],后序遍历 postorder = [9,15,7,20,3]
+输出: + + 3 + / \ + 9 20 + / \ + 15 7 +## 2 思路描述与代码 +### 2.1 思路描述(递归法) +最常见的构造树的方法就是递归了。二叉树的后序遍历的最后节点肯定是根节点,该节点在中序遍历中是个分节点,在分节点左边的节点是左子树的所有节点,右边是右子树的所有节点。利用该思路构造二叉树。 +```cpp +TreeNode* buildTree_recurse(inorder_begin, inorder_len, postorder_begin, postorder_len){ + 若中序遍历长度为 0 ,返回空指针; + 构建根节点 root, 值为 *(postorder_begin + postorder_len - 1) ; + 找到 *(postorder_begin + postorder_len - 1) 在中序遍历中的位置 idx; + //递归左右子树 + root->left = buildTree_recurse(inorder_begin, idx, postorder_begin, idx); + root->right = buildTree_recurse(inorder_begin + idx + 1, inorder_len - idx - 1, postorder_begin + idx, postorder_len - idx - 1); + 返回 root; +} +``` + +### 2.2 代码 +```cpp +typedef vector::iterator iter; +TreeNode* buildTree(vector& inorder, vector& postorder) { + return buildTree_recurse(inorder.begin(), inorder.size(), postorder.begin(), postorder.size()); +} +TreeNode* buildTree_recurse(iter inorder_begin, int inorder_len, iter postorder_begin, int postorder_len){ + if(inorder_len == 0) return nullptr; + TreeNode* root = new TreeNode(*(postorder_begin + postorder_len - 1)); + int i; + for( i = 0; i < inorder_len; i++ ){ + if(*(inorder_begin + i) == *(postorder_begin + postorder_len - 1)) break; + } + root->left = buildTree_recurse(inorder_begin, i, postorder_begin, i); + root->right = buildTree_recurse(inorder_begin + i + 1, inorder_len - i - 1, postorder_begin + i, postorder_len - i - 1); + return root; + } +``` + +## 3 思考与拓展 +### 3.1 思考 +本题主要利用二叉树中序和后序遍历的特点递归构造二叉树,思路与利用前序和后序遍历构造二叉树一致。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +递归法|O(n)|O(n) +#### 3.1.3 难点分析 +1. 需要考虑边界条件即遍历长度为 0 的时候 +2. 找到递归的表达式 +### 3.2 拓展 +如果让你从前序遍历和后序遍历构造二叉树呢?如果能,构造的二叉树是唯一的吗? diff --git a/2018.12.09-leetcode106/Despacito.md b/2018.12.09-leetcode106/Despacito.md new file mode 100644 index 000000000..3ce7dc02f --- /dev/null +++ b/2018.12.09-leetcode106/Despacito.md @@ -0,0 +1,48 @@ +# LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal +## 1. Description + +Given inorder and postorder traversal of a tree, construct the binary tree. + +**Note:** + +You may assume that duplicates do not exist in the tree. + +For example, given + +inorder = [9,3,15,20,7] + +postorder = [9,15,7,20,3] + +Return the following binary tree: + + 3 + / \ + 9 20 + / \ + 15 7 + +## 2. Solution +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def buildTree(self, inorder, postorder): + """ + :type inorder: List[int] + :type postorder: List[int] + :rtype: TreeNode + """ + if len(postorder) == 0: + return None + if len(postorder) == 1: + return TreeNode(postorder[0]) + root = TreeNode(postorder.pop()) + root.left = self.buildTree(inorder[:inorder.index(root.val)], postorder[:inorder.index(root.val)]) + root.right = self.buildTree(inorder[inorder.index(root.val)+1:], postorder[inorder.index(root.val):]) + return root +``` \ No newline at end of file diff --git a/2018.12.09-leetcode106/FFFro.md b/2018.12.09-leetcode106/FFFro.md new file mode 100644 index 000000000..f32a83742 --- /dev/null +++ b/2018.12.09-leetcode106/FFFro.md @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode buildTree(int[] inorder, int[] postorder) { + if (inorder.length == 0 || postorder.length == 0) + return null; + return build(inorder,0,inorder.length-1,postorder,0,postorder.length-1); + } + + private TreeNode build(int[] inorder, int start1, int end1, int[] postorder, int start2, int end2) { + int rootValue = postorder[end2]; + TreeNode root = new TreeNode(rootValue); + if (start2 == end2) + return root; + int temp = start1; + while (inorder[temp] != rootValue && temp <= end1){ + temp++; + } + int leftLength = temp - start1; + int leftEnd = start2 + leftLength - 1; + if (leftLength > 0) + root.left = build(inorder,start1,temp-1,postorder,start2,leftEnd); + if (leftLength < end2 - start2) + root.right = build(inorder,temp+1,end1,postorder,leftEnd+1,end2-1); + return root; + } +} diff --git a/2018.12.09-leetcode106/GatesMa.md b/2018.12.09-leetcode106/GatesMa.md new file mode 100644 index 000000000..a889c751a --- /dev/null +++ b/2018.12.09-leetcode106/GatesMa.md @@ -0,0 +1,35 @@ +# c++ +```cpp +/** + * 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* buildTree(vector& inorder, vector& postorder) { + return driver(postorder, inorder, 0, postorder.size() - 1, 0, inorder.size() - 1); + } + TreeNode* driver(vector& postorder, vector& inorder, int p_lo, int p_hi, int i_lo, int i_hi) { + if (p_lo > p_hi) return NULL; + if (p_lo == p_hi) return new TreeNode(postorder[p_hi]); + int node_val = postorder[p_hi]; + int index_in = this->find(inorder, i_lo, i_hi, node_val); + int pre_left_len = index_in - i_lo; + TreeNode* node = new TreeNode(node_val); + node->left = driver(postorder, inorder, p_lo, p_lo + pre_left_len - 1, i_lo, index_in - 1); + node->right = driver(postorder, inorder, p_lo + pre_left_len, p_hi - 1, index_in + 1, i_hi); + return node; + } + int find(vector& vec, int low, int high, int val) { + for (int i = low; i <= high; ++i) { + if (vec[i] == val) return i; + } + return -1; + } +}; +``` diff --git a/2018.12.09-leetcode106/Istoryforever.md b/2018.12.09-leetcode106/Istoryforever.md new file mode 100644 index 000000000..276865ef2 --- /dev/null +++ b/2018.12.09-leetcode106/Istoryforever.md @@ -0,0 +1,35 @@ +leetcode of 106 +``` +/** + * 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 * buildTree(vector& inorder, vector& postorder,int s,int t,int & i) { + if(s == t) return nullptr; + TreeNode * root = new TreeNode(postorder[i--]); + int val = root->val; + if(s >= t-1) return root; + int index = find(inorder.begin()+s,inorder.begin()+t,val) - inorder.begin(); + if(index != t-1){ + root->right = buildTree(inorder,postorder,index+1,t,i); + } + if(index != s){ + root->left = buildTree(inorder,postorder,s,index,i); + } + + return root; + + } + TreeNode* buildTree(vector& inorder, vector& postorder) { + int i = inorder.size()-1; + return buildTree(inorder,postorder,0,inorder.size(),i); + } +}; +``` diff --git a/2018.12.09-leetcode106/MQQM.cpp b/2018.12.09-leetcode106/MQQM.cpp new file mode 100644 index 000000000..cdef60fa1 --- /dev/null +++ b/2018.12.09-leetcode106/MQQM.cpp @@ -0,0 +1,46 @@ +/* + 题目: + 根据一棵树的中序遍历与后序遍历构造二叉树。 + + 参考: + https://blog.csdn.net/u014265347/article/details/76400400 +*/ + +/** + * 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* buildTree(vector& inorder, vector& postorder) { + int l1 = 0; + int l2 = 0; + int r1 = inorder.size() - 1; + int r2 = postorder.size() - 1; + return build(inorder, postorder, l1, r1, l2, r2); + } + TreeNode* build(vector& inorder, vector& postorder, int l1, int r1, int l2, int r2){ + if(l2 > r2){ + return NULL; + } + + int root_val = postorder[r2]; + TreeNode* root = new TreeNode(root_val); + + int idx; + for(idx = l1; idx <= r1; idx++){ + if(inorder[idx] == root_val){ + break; + } + } + root->left = build(inorder, postorder, l1, idx - 1, l2, l2 + (idx - l1) - 1); + root->right = build(inorder, postorder, idx + 1, r1, l2 + (idx - l1), r2 - 1); + + return root; + } +}; diff --git a/2018.12.09-leetcode106/Ostrichcrab.md b/2018.12.09-leetcode106/Ostrichcrab.md new file mode 100644 index 000000000..f50804a1a --- /dev/null +++ b/2018.12.09-leetcode106/Ostrichcrab.md @@ -0,0 +1,35 @@ +``` + +/** + * 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* buildTree(vector& inorder, vector& postorder) { + return buildTree(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); + } + + TreeNode* buildTree(vector& inorder, vector& postorder, int in_left, int in_right, int post_left, int post_right){ + if (in_left > in_right || post_left > post_right) + return NULL; + int rootVal = postorder[post_right];// 后序序遍历中的最后一个节点为当前树的根节点 + TreeNode* root = new TreeNode(rootVal); + // 在中序序列中找到当前根节点 + int index = distance(inorder.begin(), find(inorder.begin(), inorder.end(), rootVal)); + // 算出左子树和右子树的节点个数 + int left_num = index - in_left; + int right_num = in_right - index; + // 最后递归构建左右子树 + root->left = buildTree(inorder, postorder, in_left, index - 1, post_left, post_left + left_num - 1); + root->right = buildTree(inorder, postorder, index + 1, in_right, post_left + left_num, post_right - 1); + return root; + } +}; + +``` diff --git a/2018.12.09-leetcode106/Sagittarius.md b/2018.12.09-leetcode106/Sagittarius.md new file mode 100644 index 000000000..f56a6dab1 --- /dev/null +++ b/2018.12.09-leetcode106/Sagittarius.md @@ -0,0 +1,35 @@ +``` +/** + * 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* buildTree(vector& inorder, vector& postorder) { + return rebuildTree(0,inorder.size()-1,0,postorder.size()-1,inorder,postorder); + } + TreeNode* rebuildTree(int inL,int inR,int postL,int postR,vector& inorder,vector& postorder) + { + if(inL>inR) + return nullptr; + TreeNode* root=new TreeNode(postorder[postR]); + int k; + for(int i=0;i<=inR;i++) + if(inorder[i]==postorder[postR]) + { + k=i; + break; + } + int nump=k-inL; + root->left=rebuildTree(inL,k-1,postL,postL+nump-1,inorder,postorder); + root->right=rebuildTree(k+1,inR,postL+nump,postR-1,inorder,postorder); + + return root; + } +}; +``` diff --git a/2018.12.09-leetcode106/Sunny.md b/2018.12.09-leetcode106/Sunny.md new file mode 100644 index 000000000..846c35d40 --- /dev/null +++ b/2018.12.09-leetcode106/Sunny.md @@ -0,0 +1,28 @@ +```java +class Solution { + private int i = 0; + public TreeNode buildTree(int[] inorder, int[] postorder) { + if (postorder == null || postorder.length == 0) + return null; + if (postorder.length > i && inorder.length > 0) { + int n = inorder.length-1; + for (; n>=0; n--) { + if (inorder[n] == postorder[postorder.length-1-i]) + break; + } + if (n>=0) { + TreeNode node = new TreeNode(postorder[postorder.length-1-i]); + i++; + if (postorder.length > i) { + node.right = buildTree(Arrays.copyOfRange(inorder, n+1, inorder.length), postorder); + if (postorder.length > i) { + node.left = buildTree(Arrays.copyOfRange(inorder, 0, n), postorder); + } + } + return node; + } + } + return null; + } +} +``` diff --git a/2018.12.09-leetcode106/TheRocket.md b/2018.12.09-leetcode106/TheRocket.md new file mode 100644 index 000000000..c4557cc80 --- /dev/null +++ b/2018.12.09-leetcode106/TheRocket.md @@ -0,0 +1,32 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode buildTree(int[] inorder, int[] postorder) { + Map map = new HashMap<>(); + for (int i = 0; i < inorder.length; ++i) { + map.put(inorder[i], i); + } + return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, map); + } + + private TreeNode buildTree(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd, Map map) { + if (inBegin > inEnd || postBegin > postEnd) { + return null; + } + TreeNode root = new TreeNode(postorder[postEnd]); + int i = map.get(root.val); + int leftEnd = postBegin + i - inBegin - 1; + root.left = buildTree(inorder, inBegin, i - 1, postorder, postBegin, leftEnd, map); + root.right = buildTree(inorder, i + 1, inEnd, postorder, leftEnd + 1, postEnd - 1, map); + return root; + } +} +``` diff --git a/2018.12.09-leetcode106/Typing.txt b/2018.12.09-leetcode106/Typing.txt new file mode 100644 index 000000000..8e3c3af4c --- /dev/null +++ b/2018.12.09-leetcode106/Typing.txt @@ -0,0 +1,49 @@ +public class Main106 { + + public static void main(String[] args){ + Main106 main = new Main106(); + main.test(); + } + + public void test(){ + TreeNode node = buildTree(new int[]{9,3,15,20,7},new int[]{9,15,7,20,3}); + System.out.println(node); + } + + public TreeNode buildTree(int[] inorder, int[] postorder) { + int iLen = inorder.length; + int pLen = postorder.length; + if (iLen==0&&pLen==0) + return null; + Map iMap = new HashMap<>(); + for (int i = 0;i iMap){ + TreeNode tree = new TreeNode(postOrder[pEnd]); + tree.left = null; + tree.right = null; + if (iStart==iEnd&&pStart==pEnd) + return tree; + int pos = iMap.get(postOrder[pEnd]); + int leftLen = pos-iStart; + int rightLen = iEnd-pos; + if (leftLen>0){ + tree.left = createNode(postOrder,iStart,pos-1,pStart,pEnd-rightLen-1,iMap); + } + if (rightLen>0){ + tree.right = createNode(postOrder,pos+1,iEnd,pEnd-rightLen,pEnd-1,iMap); + } + return tree; + } + + + private class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } +} diff --git a/2018.12.09-leetcode106/WhiteNight.md b/2018.12.09-leetcode106/WhiteNight.md new file mode 100644 index 000000000..44b329b97 --- /dev/null +++ b/2018.12.09-leetcode106/WhiteNight.md @@ -0,0 +1,65 @@ +```java +/** + * 从中序与后序遍历序列构造二叉树 + */ +public class Tree17 { + public static class TreeNode { + int data; + TreeNode left; + TreeNode right; + + TreeNode(int val) { + data = val; + } + } + + public TreeNode buildTree(int[] inorder, int[] postorder) { + if (postorder == null || inorder == null || postorder.length == 0) + return null; + return buildCore(postorder, 0,postorder.length - 1,inorder, 0, inorder.length - 1); + } + + private TreeNode buildCore(int[] postorder, int postSt, int postEnd, int[] inorder, int inSt, int inEnd){ + int rootValue = postorder[postEnd]; + TreeNode root = new TreeNode(rootValue); + + if (postSt == postEnd) + return root; + + int rootInorder = inSt; + while (inorder[rootInorder] != rootValue && rootInorder <= inEnd) + rootInorder++; + + int leftLength = rootInorder - inSt; //左子树的长度 + int leftPostEnd = postSt + leftLength - 1; //后序序列中左子树的最后一个节点 + + // 左子树非空 + if (leftLength > 0){ + root.left = buildCore(postorder,postSt, leftPostEnd, inorder, inSt, rootInorder-1); + } + + // 右子树非空 + if (leftLength < postEnd - postSt){ + root.right = buildCore(postorder, leftPostEnd+1, postEnd-1, inorder, rootInorder+1, inEnd); + } + + return root; + } + + private void inOrder(TreeNode root){ + if (root != null){ + inOrder(root.left); + System.out.print(root.data + " "); + inOrder(root.right); + } + } + + public static void main(String[] args) { + Tree17 t = new Tree17(); + int[] inorder = {9, 3, 15, 20, 7}; + int[] postorder = {9, 15, 7, 20, 3}; + TreeNode resTree = t.buildTree(inorder, postorder); + t.inOrder(resTree); + } +} +``` \ No newline at end of file diff --git a/2018.12.09-leetcode106/fish.md b/2018.12.09-leetcode106/fish.md new file mode 100644 index 000000000..0497119aa --- /dev/null +++ b/2018.12.09-leetcode106/fish.md @@ -0,0 +1,64 @@ +``` +public class Solution { + public static TreeNode binaryTree(TreeNode node, List aftOrder, List inOrder) { + if (!aftOrder.isEmpty()){ + int size = aftOrder.size(); + Integer val = aftOrder.get(aftOrder.size() - 1); + int index = inOrder.indexOf(val); + + List leftAftOrder = aftOrder.subList(0, index); + List rightAftOrder = aftOrder.subList(index, size - 1); + + List leftInOrder = inOrder.subList(0, index); + List rightInOrder = inOrder.subList(index + 1, size); + + if (node == null) { + node = new TreeNode(val, null, null); + } + + TreeNode leftNode = null, rightNode = null; + if (!leftAftOrder.isEmpty()){ + leftNode = new TreeNode(leftAftOrder.get(leftAftOrder.size() - 1), null, null); + node.setLeft(leftNode); + } + if (!rightAftOrder.isEmpty()){ + rightNode = new TreeNode(rightAftOrder.get(rightAftOrder.size() - 1), null, null); + node.setRight(rightNode); + } + + binaryTree(leftNode, leftAftOrder, leftInOrder); + binaryTree(rightNode, rightAftOrder, rightInOrder); + } + return node; + } + + public static void main(String[] args) { + List aftOrder = new ArrayList<>(); + aftOrder.add(22); + aftOrder.add(16); + aftOrder.add(9); + aftOrder.add(15); + aftOrder.add(7); + aftOrder.add(20); + aftOrder.add(3); + List inOrder = new ArrayList<>(); + inOrder.add(22); + inOrder.add(9); + inOrder.add(16); + inOrder.add(3); + inOrder.add(15); + inOrder.add(20); + inOrder.add(7); + System.out.println(binaryTree(null, aftOrder, inOrder)); + } +} + +@Data +@AllArgsConstructor +@NoArgsConstructor +@ToString +class TreeNode { + private int val; + private TreeNode left; + private TreeNode right; +} \ No newline at end of file diff --git a/2018.12.09-leetcode106/marguerite.md b/2018.12.09-leetcode106/marguerite.md new file mode 100644 index 000000000..76167cc73 --- /dev/null +++ b/2018.12.09-leetcode106/marguerite.md @@ -0,0 +1,66 @@ +根据一棵树的中序遍历与后序遍历构造二叉树。 +注意: 你可以假设树中没有重复的元素。 +例如,给出 +中序遍历 inorder = [9,3,15,20,7] 后序遍历 postorder = [9,15,7,20,3] 返回如下的二叉树: +3 +/ +9 20 / +15 7 +思路: + 后序遍历的最后一个元素就是树的根节点,在中序遍历的序列中找值为r的位置idx,idx将中序遍历序列分为左右2个子树, + 对应可以将后序遍历的序列分在2个子树上,递归对其求解。 + public class Solution{ + public TreeNode buildTree(int[] inorder, int[] postorder){ + + //参数检验 + if(inorder == null || postorder == null || inorder.length == 0 || inorder.length != postorder.length){ + return null; + } + //构建二叉树 + return solve(inorder,0,inorder.length-1,postorder,0,postorder.length-1); + } + //构建二叉树 + @param inorder 中序遍历结果 + @param x 中序遍历开始位置 + @param y 中序遍历结束位置 + @param postorder 后序遍历结果 + @param i 后序遍历开始位置 + @param j 后序遍历结束位置 + @return 二叉树 + + public TreeNode solve(int[] inorder,int x,int y, int[] postorder ,int i, int j){ + if(x >= 0 && x <=y && i>=0 && i<=j){ + //只有一个元素(此时有i=j) + if(x == y){ + return new TreeNode(postorder[j]); + } + //多于一个元素,此时有i0){ + //i,i+leftlength-1,前序遍历左子树起始,结束位置 + root.left = solve(inorder,x,idx-1,postorder,i,i+leftLength-1); + } + //构建右子树 + int rightLength = y-idx; + if(rightLength >0){ + //i+leftlength,j-1,前序遍历右子树起始,结束位置 + root.right = solve(inorder,idx+1,y,postorder,i+leftLength,j-1); + } + return root; + }else{ + return null; + } + } + return null; + } + } + } diff --git a/2018.12.09-leetcode106/sourcema.md b/2018.12.09-leetcode106/sourcema.md new file mode 100644 index 000000000..3da61cc3b --- /dev/null +++ b/2018.12.09-leetcode106/sourcema.md @@ -0,0 +1,39 @@ +# LeetCode 106 + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + class Solution { + public TreeNode buildTree(int[] inorder, int[] postorder) { + TreeNode node=InPosArrGenerateTree(inorder,postorder,0,inorder.length-1,0,postorder.length-1); + return node; + } + public TreeNode InPosArrGenerateTree(int[] inArr,int[] posArr,int inStart,int inEnd, + int posStart,int posEnd) {//中序和后序 + if (posStart>posEnd) { + return null; + } + TreeNode head = new TreeNode(posArr[posEnd]); + int index = findHeadInArr(inArr, inStart, inEnd,posArr[posEnd]); + head.left = InPosArrGenerateTree(inArr, posArr, inStart,index-1, posStart, posStart+index-1-inStart); + head.right = InPosArrGenerateTree(inArr, posArr, index+1, inEnd, posStart+index-inStart, posEnd-1); + return head; + } + public int findHeadInArr(int[] inArr, int inStart, int inEnd,int target) { + int index=0; + for (int i = inStart; i <=inEnd; i++) { + if (inArr[i] == target) { + index=i; + break; + } + + } + return index; + + } + } diff --git a/2018.12.09-leetcode106/zjukk.md b/2018.12.09-leetcode106/zjukk.md new file mode 100644 index 000000000..080405207 --- /dev/null +++ b/2018.12.09-leetcode106/zjukk.md @@ -0,0 +1,18 @@ +class Solution { +public: + TreeNode* buildTree(vector& inorder, vector& postorder) { + return buildTree(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1); + } + TreeNode* buildTree(vector& inorder, int iLeft, int iRight, vector& postorder, int pLeft, int pRight) { + if (iLeft > iRight) return NULL; + TreeNode* root = new TreeNode(postorder[pRight]); + int i = iLeft; + for (; i <= iRight; ++i) { + if (inorder[i] == root->val) + break; + } + root->left = buildTree(inorder,iLeft,i-1,postorder,pLeft,pLeft-iLeft+i-1); + root->right = buildTree(inorder,i+1,iRight,postorder,pLeft-iLeft+i,pRight-1); + return root; + } +}; diff --git "a/2018.12.09-leetcode106/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.09-leetcode106/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..8d9c65552 --- /dev/null +++ "b/2018.12.09-leetcode106/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,32 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + TreeNode biuld(int[] in,int inl,int inr,int[] post,int pl,int pr){ + if(inr map=new HashMap(); + //由于之后查找很频繁,把值存在哈希表里.查找快 + for(int i=0;i map2=new HashMap(); + public TreeNode buildTree(int[] a, int a1, int a2, int[] b, int b1, int b2) { + if (a1 > a2 || b1 > b2) { return null; } + int mid = map2.get(b[b2]); + int count = mid - a1; + TreeNode root = new TreeNode(b[b2]); + root.left = buildTree(a, a1, mid - 1, b, b1, b1 + count - 1); + root.right = buildTree(a, mid + 1, a2, b, b1 + count, b2 - 1); + return root; + } + + public static TreeNode inpos(int[] in,int ii,int ij,int[] pos,int si,int sj,HashMap map) + { + if(ii>ij) + return null; + //根是后序的最后一个元素 + TreeNode head=new TreeNode(pos[sj]); + int index=map.get(pos[sj]); + //index中序节点前有的节点 + int count = index-ii; + head.left=inpos(in, ii, index-1, pos, si, si+count-1, map); + head.right=inpos(in, index+1, ij, pos, si+count, sj-1, map); +// head.left=inpos(in, ii, index-1, pos, si, si+index-1-ii, map); +// head.right=inpos(in, index+1, ij, pos, si+index-ii, sj-1, map); + return head; + } + + private static void print(TreeNode tree, int key, int direction) { + + if(tree != null) { + + if(direction==0) // tree是根节点 + System.out.printf("%2d is root\n", tree.val); + else // tree是分支节点 + System.out.printf("%2d is %2d's %6s child\n",tree.val,key, direction==1?"right" : "left"); + + print(tree.left, tree.val, -1); + print(tree.right,tree.val, 1); + } + } + + public static void print(TreeNode node) + { + if (node != null) + print(node, node.val, 0); + } +} + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} +``` diff --git "a/2018.12.09-leetcode106/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.09-leetcode106/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..accd2b1fd --- /dev/null +++ "b/2018.12.09-leetcode106/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,50 @@ +### [106. Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) + +**题目描述** +> 给定中序和后序遍历,重构二叉树。 + +> 假设树中没有重复结点。 + +**例子** +中序遍历 inorder = [9,3,15,20,7] +后序遍历 postorder = [9,15,7,20,3] +返回如下的二叉树: + + 3 + / \ + 9 20 + / \ + 15 7 + + +**思想** +中序 - 左根右;后序 - 左右根 +(递归) +Trick - 改进:用pop(),不再对postorder切片操作。注意先root.right = xxx,再操作root.left = xxx。 + +**解法** +```python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def buildTree(self, inorder, postorder): + """ + :type inorder: List[int] + :type postorder: List[int] + :rtype: TreeNode + """ + if not inorder: + return None + root = TreeNode(postorder[-1]) + idx = inorder.index(postorder.pop()) + + root.right = self.buildTree(inorder[idx+1:], postorder) + root.left = self.buildTree(inorder[:idx], postorder) + + return root +``` \ No newline at end of file diff --git "a/2018.12.09-leetcode106/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.09-leetcode106/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..5b44fe29e --- /dev/null +++ "b/2018.12.09-leetcode106/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,32 @@ +``` +/** + * 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* buildTree(vector& inorder, vector& postorder) { + return build(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1); + } + + TreeNode *build(vector& inorder, int ileft, int iright, vector& postorder, int pleft, int pright) + { + if(ileft>iright || pleft>pright) return NULL; + + int i; + for(i=ileft; i<=iright; i++) + if(inorder[i] == postorder[pright]) break; + + TreeNode *root = new TreeNode(postorder[pright]); + root->left = build(inorder, ileft, i-1, postorder, pleft, pleft+i-ileft-1); + root->right = build(inorder, i+1, iright, postorder, pleft+i-ileft, pright-1); + + return root; + } +}; +``` diff --git "a/2018.12.09-leetcode106/\350\216\216\350\216\216.md" "b/2018.12.09-leetcode106/\350\216\216\350\216\216.md" new file mode 100644 index 000000000..3453ebdf5 --- /dev/null +++ "b/2018.12.09-leetcode106/\350\216\216\350\216\216.md" @@ -0,0 +1,16 @@ +``` +class Solution: + def buildTree(self, inorder, postorder): + """ + :type inorder: List[int] + :type postorder: List[int] + :rtype: TreeNode + """ + if not postorder: + return None + root = TreeNode(postorder[-1]) + n = inorder.index(root.val) + root.left = self.buildTree(inorder[:n],postorder[0:n]) + root.right = self.buildTree(inorder[n+1:],postorder[n:-1]) + return root +``` diff --git a/2018.12.1-leetcode387/-.md b/2018.12.1-leetcode387/-.md new file mode 100644 index 000000000..bebdea1f0 --- /dev/null +++ b/2018.12.1-leetcode387/-.md @@ -0,0 +1,26 @@ +public class Solution_387 { + public int firstUniqChar(String s) { + int index = -1 ; + Map map = new LinkedHashMap(); + for (int i = 0; i < s.length(); i++) { + Integer count = map.get(s.charAt(i)); + map.put(s.charAt(i), count == null ? 0 : ++count); + } + Set> entrySet = map.entrySet(); + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext()) { + + Map.Entry next = iterator.next(); + //System.out.println(next.getKey()+"-"+next.getValue()); + if (next.getValue() == 0) { + index = next.getKey(); + break; + } + } + return s.indexOf(index); + } + + public static void main(String[] args) { + System.out.println(new Solution_387().firstUniqChar("dddccdbba")); + } +} diff --git a/2018.12.1-leetcode387/Avalon.md b/2018.12.1-leetcode387/Avalon.md new file mode 100644 index 000000000..259d3a290 --- /dev/null +++ b/2018.12.1-leetcode387/Avalon.md @@ -0,0 +1,41 @@ +class Solution { + public int firstUniqChar(String s) { + char[] storeArr = new char[26];//暂时存储数组,根据出现的顺序 + int[] numArr = new int[26];//存储数目 + + char[] sArr = s.toCharArray(); + int len = sArr.length; + for (int i=0;i +输出:返回 0
+ +#### 1.3.2 样例2 +输入: s = "loveleetcode"
+输出: 2
+## 2 思路描述与代码 +### 2.1 思路描述(字典法) +dict[c] 记录字符 c 的数目,一遍扫描记录字符串 s 中的所有字符的数目
+然后再一遍扫描 s,当 s 中字符 c 只出现一次即dict[c] = 1时返回下标,如果没有这样的字符则返回-1
+ +比如输入s = "leetcode",一遍扫描后有:
+dict['c'] = 1, dict['d'] = 1, dict['e'] = 3, dict['l'] = 1, dict['o'] = 1, dict['t'] = 1
+然后再次一遍扫描s,发现dict['l'] = 1,返回此时遍历的索引 0
+ +### 2.2 代码 +```cpp +int firstUniqChar(string s) { + vector dict(26, 0); + int len = s.size(); + for( int i = 0; i < len; i++ ) dict[s[i] - 'a'] += 1; + for( int i = 0; i < len; i++ ){ + if(dict[s[i] - 'a'] == 1) return i; + } + return -1; +} +``` +## 3 思考与拓展 +### 3.1 思考 +#### 3.1.1 其他方法 +##### 3.1.1.1 字典+队列法 +dict[c] 记录字符 c 的数目,队列 q 保存的是在遍历过程中在 s 中按前后顺序出现出现过的字符极其下标,相同字符只记录一次
+ +然后遍历队列里面的元素,当 s 中字符 c 只出现一次即dict[c] = 1时返回下标。 + +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +字典法|O(1)|O(n) +字典+队列法|O(n)|O(n),平均复杂度更低,应该运行更快 +#### 3.1.3 难点分析 +1. 如何查重即多个相同的字符 +2. 如何按先后顺序记录只出现一次的字符 +### 3.2 拓展 +如果给你的是链表数据或者数组数据呢? diff --git a/2018.12.1-leetcode387/FFFro.md b/2018.12.1-leetcode387/FFFro.md new file mode 100644 index 000000000..1fcc8ad4d --- /dev/null +++ b/2018.12.1-leetcode387/FFFro.md @@ -0,0 +1,37 @@ +public class Solution { + public int FirstNotRepeatingChar(String str) { + if (str.length() == 0) + return -1; + int index = 1; + int[] temp = new int[26]; + for (int i = 0; i < str.length(); i++) { + int a = (int)str.charAt(i) - 97; + if (temp[a] == 0){ + temp[a] = index++; + }else { + temp[a] = -1; + } + } + char c = '#'; + int res= Integer.MAX_VALUE; + for (int j = 0; j < temp.length; j++) { + if (temp[j] > 0){ + if (temp[j] < res){ + res = temp[j]; + c = (char) (j+97); + } + } + } + if (c == '#'){ + return -1; + } + for (int k = 0; k < str.length(); k++) { + if (str.charAt(k) == c){ + return k; + } + } + return -1; + } + + +} diff --git a/2018.12.1-leetcode387/GatesMa.md b/2018.12.1-leetcode387/GatesMa.md new file mode 100644 index 000000000..9a7646fe9 --- /dev/null +++ b/2018.12.1-leetcode387/GatesMa.md @@ -0,0 +1,20 @@ +# c++ +```cpp +class Solution { +public: + int firstUniqChar(string s) { + int chnum[26]; + memset(chnum, 0, sizeof(chnum)); + int len = s.length(); + for(int i=0;i m; + //string ss(s); + for(auto c : s){ + if(m.count(c) == 0) m[c]=1; + else m[c]++; + } + for(auto i = s.begin();i!=s.end();i++){ + if(m[*i] == 1) return i-s.begin(); + } + return -1; + +} +}; diff --git a/2018.12.1-leetcode387/MQQM.cpp b/2018.12.1-leetcode387/MQQM.cpp new file mode 100644 index 000000000..f413e5e68 --- /dev/null +++ b/2018.12.1-leetcode387/MQQM.cpp @@ -0,0 +1,39 @@ +/* + 题目: + 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 + + 案例: + s = "leetcode" 返回 0. + s = "loveleetcode", 返回 2. + + 注意事项:您可以假定该字符串只包含小写字母。 +*/ +class Solution { +public: + int firstUniqChar(string s) { + int len=s.size(); + if(len<=1){//长度为0返回-1,长度为1返回0 + return len-1; + } + + //长度大于等于2时 + int ret_idx=-1; + for(int i=0; i<=len-1; i++){ + int j=0; + for(; j<=len-1; j++){ + if(i==j){ + continue; + } + if(s[i]==s[j]){//s[i] is not unique + break; + } + } + if(j==len){ + ret_idx=i; + break; + } + } + + return ret_idx; + } +}; diff --git a/2018.12.1-leetcode387/MQQM2.cpp b/2018.12.1-leetcode387/MQQM2.cpp new file mode 100644 index 000000000..94f15dabe --- /dev/null +++ b/2018.12.1-leetcode387/MQQM2.cpp @@ -0,0 +1,51 @@ +/* + 题目: + 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 + + 案例: + s = "leetcode" 返回 0. + s = "loveleetcode", 返回 2. + + 注意事项:您可以假定该字符串只包含小写字母。 +*/ +class Solution { +public: + int firstUniqChar(string s) { + int len=s.size(); + if(len<=1){//长度为0返回-1,长度为1返回0 + return len-1; + } + + //长度大于等于2时 + int ret_idx=-1; + + for(int i=0; i<=len-1; i++){ + if(s[i]=='#'){ + continue; + } + + int j=0; + for(; j<=len-1; j++){ + if( i==j || s[j]=='#' ){ + continue; + } + + if(s[i]==s[j]){//s[i] is not unique + char c=s[j]; + for(int k=0; k<=len-1; k++){ + if(c==s[k]){ + s[k]='#'; + } + } + break;//break for(j) + } + }//end of for(j) + if(j==len){ + ret_idx=i; + break; + } + }//end of for(i) + + return ret_idx; + } +}; diff --git a/2018.12.1-leetcode387/MQQM3.cpp b/2018.12.1-leetcode387/MQQM3.cpp new file mode 100644 index 000000000..8474afa0e --- /dev/null +++ b/2018.12.1-leetcode387/MQQM3.cpp @@ -0,0 +1,36 @@ +/* + 题目: + 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 + + 案例: + s = "leetcode" 返回 0. + s = "loveleetcode", 返回 2. + + 注意事项:您可以假定该字符串只包含小写字母。 +*/ +class Solution { +public: + int firstUniqChar(string s) { + int len=s.size(); + if(len<=1){//长度为0返回-1,长度为1返回0 + return len-1; + } + + //长度大于等于2时 + int* p=new int[26]{0}; + for(int i=0; i<=len-1; i++){//记录每个字母出现的次数 + p[s[i]-'a']++; + } + + int ret_idx=-1; + for(int i=0; i<=len-1; i++){//找第一个出现次数为1的字母的索引 + if(p[s[i]-'a']!=1){ + continue; + } + ret_idx=i; + break; + } + + return ret_idx; + } +}; diff --git a/2018.12.1-leetcode387/Ostrichcrab.md b/2018.12.1-leetcode387/Ostrichcrab.md new file mode 100644 index 000000000..467500a6d --- /dev/null +++ b/2018.12.1-leetcode387/Ostrichcrab.md @@ -0,0 +1,19 @@ +``` +class Solution { +public: + int firstUniqChar(string s) { + int len = s.length(); + if(len==1) return 0; + map mp; + int ans = -1; + for(int i = len-1; i >= 0; i--){ + mp[s[i]]++; + } + for(int i = len-1; i>= 0; i--){ + if(mp[s[i]]==1) ans = i; + } + return ans; + + } +}; +``` diff --git a/2018.12.1-leetcode387/Sagittarius.md b/2018.12.1-leetcode387/Sagittarius.md new file mode 100644 index 000000000..b23e58526 --- /dev/null +++ b/2018.12.1-leetcode387/Sagittarius.md @@ -0,0 +1,18 @@ +``` +class Solution { +public: + int firstUniqChar(string s) { + int a[26]={0}; + for(int i=0;i map = new LinkedHashMap<>(s.length()); + for (int i=0; i < s.length(); i++) { + char c = s.charAt(i); + if (map.containsKey(c)) { + map.put(c, -1); + } else { + map.put(c, i); + } + } + for (int value : map.values()) { + if (value != -1) { + return value; + } + } + return -1; + } +} +``` diff --git a/2018.12.1-leetcode387/TheRocket.md b/2018.12.1-leetcode387/TheRocket.md new file mode 100644 index 000000000..6e536229c --- /dev/null +++ b/2018.12.1-leetcode387/TheRocket.md @@ -0,0 +1,16 @@ +```java +class Solution { + public int firstUniqChar(String s) { + int[] cnt = new int[26]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - 'a']; + } + for (int i = 0; i < s.length(); ++i) { + if (cnt[s.charAt(i) - 'a'] == 1) { + return i; + } + } + return -1; + } +} +``` diff --git a/2018.12.1-leetcode387/Tony the Cyclist.md b/2018.12.1-leetcode387/Tony the Cyclist.md new file mode 100644 index 000000000..1b8b13d81 --- /dev/null +++ b/2018.12.1-leetcode387/Tony the Cyclist.md @@ -0,0 +1,22 @@ +``` +class Solution { + public int firstUniqChar(String s) { + //char[] c = s.toCharArray(); + Map m = new HashMap<>(); + for (int i = 0; i < s.length(); i++){ + if (m.containsKey(s.charAt(i))){ + m.put(s.charAt(i), m.get(s.charAt(i))+1); + } + else { + m.put(s.charAt(i), 1); + } + } + for (int i = 0; i < s.length(); i++){ + if (m.get(s.charAt(i)) == 1){ + return i; + } + } + return -1; + } +} +``` diff --git a/2018.12.1-leetcode387/WhiteNight.md b/2018.12.1-leetcode387/WhiteNight.md new file mode 100644 index 000000000..2b2e16077 --- /dev/null +++ b/2018.12.1-leetcode387/WhiteNight.md @@ -0,0 +1,61 @@ +>```java +>import java.util.LinkedHashMap; +>import java.util.Map; +> +>/** +> * 字符串中的第一个唯一字符 +> * +> */ +>public class S4 { +> public int firstUniqChar(String s) { +> Map map = new LinkedHashMap<>(); +> char[] chars = s.toCharArray(); +> +> for (int i = 0; i < chars.length; i++) { +> if (!map.containsKey(chars[i])){ +> map.put(chars[i], i); +> } +> else{ +> map.put(chars[i], -1); +> } +> } +> +> for (Map.Entry entry : map.entrySet()){ +> if (entry.getValue() != -1) +> return entry.getValue(); +> } +> +> return -1; +> } +> +> public int firstUniqChar(String s) { +> int start; +> int end; +> int result = s.length(); +> +> for (char i = 'a'; i <= 'z'; i++) { +> start = s.indexOf(i); +> end = s.lastIndexOf(i); +> if (start == end && start != -1){ +> result = Math.min(result,start); +> } +> } +> +> if (result == s.length()) +> return -1; +> else +> return result; +> } +> +> public static void main(String[] args) { +> S4 s = new S4(); +> String s1 = "leetcode"; +> String s2 = "loveleetcode"; +> int res1 = s.firstUniqChar(s1); +> int res2 = s.firstUniqChar(s2); +> System.out.println(res1); +> System.out.println(res2); +> } +>} +>``` + diff --git a/2018.12.1-leetcode387/halfofwater.md b/2018.12.1-leetcode387/halfofwater.md new file mode 100644 index 000000000..799cf58d7 --- /dev/null +++ b/2018.12.1-leetcode387/halfofwater.md @@ -0,0 +1,27 @@ +## Leetcode 387 + +``` C++ +class Solution { +public: + int firstUniqChar(string s) { + if (s.size() == 0) return -1; + if (s.size() < 2) return 0; + string alphabet = "abcdefghijklmnopqrstuvwxyz"; + map countMap; + s += '\0'; + char *sHead = (char *)s.data(); + char *head = sHead; + while (*sHead != '\0') + { + countMap[*sHead]++; + ++sHead; + } + for (int i = 0; i < s.size(); i++) { + if (countMap[s[i]] == 1){ + return i; + } + } + return -1; + } +}; +``` diff --git a/2018.12.1-leetcode387/justwe.md b/2018.12.1-leetcode387/justwe.md new file mode 100644 index 000000000..f06e6c8a9 --- /dev/null +++ b/2018.12.1-leetcode387/justwe.md @@ -0,0 +1,22 @@ +class Solution { + public int firstUniqChar(String s) { + if(null == s || 0 == s.length() ) + return -1; + int[] hash = new int[26];//记录26个字母的字符数组 + char[] array = s.toCharArray();//将字符串转为字符数组 + //通过遍历字符数组,查看字符串中每个字母出现的次数 + for(int i = 0; i < array.length; i++){ + int num = array[i] - 'a'; + + hash[num]++; + } + for(int i = 0; i < array.length; i++){//从字符串出发 + //获得26个字母的下标 + int num = array[i] - 'a'; + if(hash[num] == 1){ + return i; + } + } + return -1; + } +} diff --git a/2018.12.1-leetcode387/kiritocly.md b/2018.12.1-leetcode387/kiritocly.md new file mode 100644 index 000000000..55f077c0e --- /dev/null +++ b/2018.12.1-leetcode387/kiritocly.md @@ -0,0 +1,42 @@ + private static int solution(String input) { + //只出现一次的字符的编号,以leetcode为例 + int index = 1; + //26个英文字母,初始化一个长度为26的整形数组,第一个位置表示a的值, + //第二个位置表示b的值,依此类推,数组中有三类值,-1,0,大于等于1的整数 + //-1表示字母出现两次或两次以上,0表示从未出现,大于等于1的整数表示只出现一次 + //的字母的序号 + int[] array = new int[26]; + for (int i = 0; i < input.length(); i++) { + //将字符串中的字符转化为数组中的下标,例如a的asc码值为97,对应数组中的下标为0 + int charIndex = (int)input.charAt(i) - 97; + if (array[charIndex] == 0) { + //第一次出现,序号为index + array[charIndex] = index; + //index自增,记录下一个第一次出现的字符 + index++; + } else { + //字符已经出现过,即一个字符出现两次或者两次以上 + array[charIndex] = -1; + } + } + char result = '#'; + //遍历array数组,找到最小的index,index>=1 + //记录最小的index + int resultIndex = Integer.MAX_VALUE; + for (int j = 0; j < array.length; j++) { + if (array[j] > 0 && array[j] < resultIndex) { + resultIndex = array[j]; + result = (char)(j + 97); + } + } + if (result == '#') { + return -1; + } + //找到result在字符串中第一次出现的位置 + for (int k = 0; k < input.length(); k++) { + if (result == input.charAt(k)) { + return k; + } + } + return -1; + } diff --git a/2018.12.1-leetcode387/sourcema.md b/2018.12.1-leetcode387/sourcema.md new file mode 100644 index 000000000..6a554b1a8 --- /dev/null +++ b/2018.12.1-leetcode387/sourcema.md @@ -0,0 +1,18 @@ +# LeetCode 387 + class Solution { + public int firstUniqChar(String s) { + if (s.length() == 0 || s == null) { + return -1; + } + int[] arr = new int[26]; + for (int i = 0; i < s.length(); i++) { + arr[s.charAt(i) - 'a']++; + } + for (int i = 0; i < s.length(); i++) { + if (arr[s.charAt(i)-'a']==1) { + return i; + } + } + return -1; + } +} diff --git a/2018.12.1-leetcode387/syuan.md b/2018.12.1-leetcode387/syuan.md new file mode 100644 index 000000000..2d3b0315c --- /dev/null +++ b/2018.12.1-leetcode387/syuan.md @@ -0,0 +1,80 @@ +##### 题目 + +``` +给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 + +案例: + +s = "leetcode" +返回 0. + +s = "loveleetcode", +返回 2. + + + +注意事项:您可以假定该字符串只包含小写字母。 +``` +##### 解答一 + +``` +class Solution { + public int firstUniqChar(String s) { + int length=s.length(); + if (s.equals("")) { + return -1; + } + if (length==1) { + return 0; + } + + int i=0;//返回索引 + char temp=s.charAt(0);//用来记录每次要比较的字符 + while (i=length) { + break; + } + i++; + } + if (i>=length) { + return -1; + } + return i; + } +} +``` +>这里对于每一个数字必须要从索引0开始 因为有可能他的重复数字在前面 +> +>执行时间56ms + +##### 解法二 + +``` +class Solution { + public int firstUniqChar(String s) { + int[] freq=new int[26]; + for (int i=0; i +#include +#include +using namespace std; + +class Solution { +public: + int firstUniqChar(string s) { + map m; + for (char c : s) { + if (!m.count(c)) { + m[c] = 1; + } else { + ++m[c]; + } + } + int i = 0; + for (; i < s.size(); ++i) { + if (m[s[i]] == 1) return i; + } + if (i == s.size()) return -1; + } +}; +class Solution2 { +public: + int firstUniqChar(string s) { + int list[256] = {0}; + for (auto c : s) { + ++list[c]; + } + for (int i = 0; i < s.size(); ++i) { + if (list[s[i]] == 1) return i; + } + return -1; + } +}; diff --git "a/2018.12.1-leetcode387/\343\200\202V1ncentzzZ.md" "b/2018.12.1-leetcode387/\343\200\202V1ncentzzZ.md" new file mode 100644 index 000000000..d9e28a853 --- /dev/null +++ "b/2018.12.1-leetcode387/\343\200\202V1ncentzzZ.md" @@ -0,0 +1,35 @@ +LeetCode387:https://leetcode-cn.com/problems/first-unique-character-in-a-string/ + +给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 + +案例: + +s = "leetcode" +返回 0. + +s = "loveleetcode", +返回 2. + + +注意事项:您可以假定该字符串只包含小写字母。 + +class Solution { + + // TODO 未用indexOf版本 + // public int firstUniqChar(String s) { + // s = s.trim(); + // if("".equals(s)) return -1; + // if(s.length() == 1) return 0; + // char[] chars = s.toCharArray(); + // outer:for(int i=0; i map = new HashMap<>(); + for (int i = 0; i < s.length(); i++){ + if (map.containsKey(s.charAt(i))){ + map.put(s.charAt(i),Integer.MAX_VALUE); + }else { + map.put(s.charAt(i),i); + } + } + for (int i : map.values()){ + result = Math.min(i,result); + } + if (result == Integer.MAX_VALUE)result=-1; + return result; + } +} +``` diff --git "a/2018.12.1-leetcode387/\344\272\221\346\267\261\344\270\215\345\217\271.md" "b/2018.12.1-leetcode387/\344\272\221\346\267\261\344\270\215\345\217\271.md" new file mode 100644 index 000000000..254c50b7c --- /dev/null +++ "b/2018.12.1-leetcode387/\344\272\221\346\267\261\344\270\215\345\217\271.md" @@ -0,0 +1,16 @@ +``` +public int firstUniqChar(String s) { + if(s==null || s.trim().equals("")){ + return -1; + } + char[] chars = s.toCharArray(); + int res = -1; + for(char c : chars){ + int index = s.indexOf(c); + if(index == s.lastIndexOf(c)){ + return index; + } + } + return res; + } +``` diff --git "a/2018.12.1-leetcode387/\344\272\221\350\203\241\344\270\215\345\226\234.md" "b/2018.12.1-leetcode387/\344\272\221\350\203\241\344\270\215\345\226\234.md" new file mode 100644 index 000000000..f9fc4d3f5 --- /dev/null +++ "b/2018.12.1-leetcode387/\344\272\221\350\203\241\344\270\215\345\226\234.md" @@ -0,0 +1,13 @@ +public class Solution { + public int lengthOfLastWord(String s) { + int result = 0,i = s.length()-1; + while( i>=0 && s.charAt(i) == ' ' ){ + i--; + } + while( i>=0 && s.charAt(i) != ' '){ + result++; + i--; + } + return result; + } +} diff --git "a/2018.12.1-leetcode387/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.12.1-leetcode387/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..9b166af54 --- /dev/null +++ "b/2018.12.1-leetcode387/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,20 @@ +``` +class Solution { + public int firstUniqChar(String s) { + + char[] arr = s.toCharArray(); + int[] count = new int[26];//创建字母表数组 + for(int i =0;i number(26); + int i; + for(i=0;i 给定一字符串,找到第一个不重复字符,返回索引。如果不存在,返回-1。 + +> 假设只包含小写字母~ + +**例子** +> s = "leetcode" +return 0. + +>s = "loveleetcode", +return 2. + +**思想** +比较简单 ,方法也比较多:用字典统计出现次数、利用count函数、遍历所有字母,rfind是从后向前求索引。 + +**解法1** +```python +class Solution(object): + def firstUniqChar(self, s): + """ + :type s: str + :rtype: int + """ + dic = {} + for c in s: + dic[c] = dic.get(c, 0) + 1 + + for i, c in enumerate(s): + if dic[c] == 1: + return i + return -1 +``` +**解法2** +用一下Python自带的count函数 +```python +class Solution(object): + def firstUniqChar(self, s): + """ + :type s: str + :rtype: int + """ + dic = {} + for c in set(s): + dic[c] = s.count(c) + + for i in range(len(s)): + if dic[s[i]] == 1: + return i + return -1 +``` +**解法3** +遍历所有字母,rfind是从后向前索引。 +```python +class Solution(object): + def firstUniqChar(self, s): + """ + :type s: str + :rtype: int + """ + res = len(s) + for c in "abcdefghijklmnopqrstuvwxyz": + idx = s.find(c) + if idx != -1 and idx == s.rfind(c): + res = min(idx, res) + if res != len(s): + return res + return -1 +``` \ No newline at end of file diff --git "a/2018.12.1-leetcode387/\346\235\250.md" "b/2018.12.1-leetcode387/\346\235\250.md" new file mode 100644 index 000000000..c7d2938f6 --- /dev/null +++ "b/2018.12.1-leetcode387/\346\235\250.md" @@ -0,0 +1,14 @@ +``` + +public int firstUniqChar(String s) { + int res = -1; + for(char i ='a';i<='z';i++){ + int index = s.indexOf(i); + if(index!=-1 && index == s.lastIndexOf(i)){ + res = (res==-1 || res > index) ? index : res; + } + } + return res; +} + +``` diff --git "a/2018.12.1-leetcode387/\346\271\233\346\261\237\347\224\262\351\270\237.md" "b/2018.12.1-leetcode387/\346\271\233\346\261\237\347\224\262\351\270\237.md" new file mode 100644 index 000000000..5eb86d1bb --- /dev/null +++ "b/2018.12.1-leetcode387/\346\271\233\346\261\237\347\224\262\351\270\237.md" @@ -0,0 +1,24 @@ +``` +public int firstUniqChar(String s) { + int val = -1; + if (s == null || s.length == 0) { + return val; + } + HashMap buckets = new HashMap<>(); + char[] chars = s.toLowerCase().toCharArray(); + for (char ch : chars) { + int count = 0; + if (buckets.containsKey(ch)) { + count = 1; + } + buckets.put(ch, count + 1); + } + for (int i = 0; i < chars.length; i++) { + int firstUniq = buckets.get(chars[i]); + if (firstUniq == 1){ + val = i; + break; + } + } + return val; +} diff --git "a/2018.12.1-leetcode387/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.1-leetcode387/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..5ccc3f350 --- /dev/null +++ "b/2018.12.1-leetcode387/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,29 @@ +... +class Solution { +public: + int firstUniqChar(string s) { + if(s.length() == 1) + return 0; + if(s.length() == 0) + return -1; + + map m; + int i = 0; + for(i=0; i characters = new ArrayList<>(); + HashMap indexMap = new HashMap<>(); + for (int i = 0; i < s.length(); i++) { + Character key = s.charAt(i); + characters.add(key); + indexMap.put(key,indexMap.getOrDefault(key,0)+1); + } + for (int i = 0; i < characters.size(); i++) { + Character key = characters.get(i); + if(indexMap.get(key) == 1) { + return i; + } + } + return -1; + } +``` diff --git "a/2018.12.1-leetcode387/\351\223\201\347\224\267\347\245\236sama.md" "b/2018.12.1-leetcode387/\351\223\201\347\224\267\347\245\236sama.md" new file mode 100644 index 000000000..fb349c2aa --- /dev/null +++ "b/2018.12.1-leetcode387/\351\223\201\347\224\267\347\245\236sama.md" @@ -0,0 +1,20 @@ + +# 一 + +``` +class Solution { + public int firstUniqChar(String s) { + int[] array=new int[26]; + for(char c:s.toCharArray()){ + array[c-'a']+=1; + } + for(char c:s.toCharArray()){ + if(array[c-'a']==1)return s.indexOf(c); + } + return -1; + } +} +``` + +# 二 + diff --git "a/2018.12.1-leetcode387/\351\230\263.md" "b/2018.12.1-leetcode387/\351\230\263.md" new file mode 100644 index 000000000..4eea5f08d --- /dev/null +++ "b/2018.12.1-leetcode387/\351\230\263.md" @@ -0,0 +1,24 @@ +class Solution { + public String reverseWords(String s) { + String[] strs = s.split("\\s"); + String reverseStr = ""; + for(int i = 0; i < strs.length; i++) { + reverseStr += reverseEachWord(strs[i])+" "; + } + return reverseStr.trim(); + } + + public String reverseEachWord(String str) { + char[] chs = str.toCharArray(); + for(int i = 0; i < chs.length/2; i++) { + swap(chs, i, chs.length-1-i); + } + return String.valueOf(chs); + } + + public void swap(char[] chs, int i, int j) { + char tmp = chs[i]; + chs[i] = chs[j]; + chs[j] = tmp; + } +} diff --git "a/2018.12.1-leetcode387/\351\233\252\350\276\260.md" "b/2018.12.1-leetcode387/\351\233\252\350\276\260.md" new file mode 100644 index 000000000..99b393ce3 --- /dev/null +++ "b/2018.12.1-leetcode387/\351\233\252\350\276\260.md" @@ -0,0 +1,17 @@ +class Solution: + def firstUniqChar(self, s): + """ + :type s: str + :rtype: int + """ + + d = {} + for i in range(len(s)): + if s[i] not in d: + d[s[i]] = i + else: + d[s[i]] += len(s) + if len(s) and min(d.values()) < len(s): + return min(d.values()) + return -1 + ##224ms 打败40% diff --git "a/2018.12.1-leetcode387/\351\233\267\351\207\221.md" "b/2018.12.1-leetcode387/\351\233\267\351\207\221.md" new file mode 100644 index 000000000..eab2157e9 --- /dev/null +++ "b/2018.12.1-leetcode387/\351\233\267\351\207\221.md" @@ -0,0 +1,19 @@ +class Solution { + public int firstUniqChar(String s) { + if(s==null||s.length()<1) { + return -1; + } + int []hash = new int [26]; + for(int i=0;i map=new HashMap<>(); + for(int i=0;i> levelOrderBottom(TreeNode root) { + List> tempresult = new ArrayList<>(); + if (root == null) return tempresult; + Queue queue = new LinkedList<>(); + queue.add(root); + TreeNode current; + while (!queue.isEmpty()) { + List tl = new ArrayList<>(); + //List tn = new ArrayList<>(); + int len = queue.size(); + for (int i = 0; i < len; i++) { + current = queue.poll(); + tl.add(current.val); + if (current.left != null) + queue.add(current.left); + if (current.right != null) + queue.add(current.right); + } + tempresult.add(tl); + } + List> result = new ArrayList<>(); + int trlen = tempresult.size(); + for (int i=trlen-1;i>=0;i--){ + result.add(tempresult.get(i)); + } + return result; + } +} diff --git a/2018.12.10-leetcode107/Be a fresh man.md b/2018.12.10-leetcode107/Be a fresh man.md new file mode 100644 index 000000000..d36220936 --- /dev/null +++ b/2018.12.10-leetcode107/Be a fresh man.md @@ -0,0 +1,115 @@ +## 107_(二叉树的层次遍历 II)Binary Tree Level Order Traversal II +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)。 +### 1.2 输入与输出 +输入: +* TreeNode* root:二叉树的根节点指针 + +输出: +* vector>:自底向上的层次遍历的结果,是一个二维矢量的形式 +### 1.3 样例 +#### 1.3.1 样例1 +输入: 二叉树: [3,9,20,null,null,15,7] + + 3 + / \ + 9 20 + / \ + 15 7 + +输出: + + [ + [15,7], + [9,20], + [3] + ] + +## 2 思路描述与代码 +### 2.1 思路描述(队列BFS+堆栈) +主要利用思路就是在用队列做BFS的同时将数据记录到堆栈中,然后再利用堆栈实现自底向上的层次遍历。重点在于: +1. 在入队列的时候右节点优先进队,便于堆栈处理数据 +2. 记录堆栈中需要记录当前层的所有节点数据与节点个数 + +比如输入[3,9,20,null,null,15,7]
+首先队列BFS并记录到堆栈中,其过程主要如下:
+* 将根节点3入队;
+* 队列不空,当前层节点数据有1个,数据是3,入队的元素有[20, 9],并记录当前层数据3和节点个数1到堆栈中,此时 q = [20, 9], s = [3, 1];
+* 队列不空,当前层节点数据有2个,数据是[20, 9],入队的元素有[7, 15],并记录当前层数据[20, 9]和节点个数2到堆栈中,此时 q = [7, 15], s = [3, 1, 20, 9, 2];
+* 队列不空,当前层节点数据有2个,数据是[7, 15],无入队元素,并记录当前层数据[7, 15]和节点个数2到堆栈中,此时 q 为空, s = [3, 1, 20, 9, 2, 7, 15, 2];
+* 队列空,开始从堆栈中处理遍历的数据;
+ +等到队列空后,开始处理堆栈里面的数据,其过程主要如下:
+* 堆栈不空,获取栈顶元素2并出栈,2为当前层的节点数据,然后取出堆栈中2个元素[15, 7],此时s = [3, 1, 20, 9, 2], 遍历结果为[[15, 7]];
+* 堆栈不空,获取栈顶元素2并出栈,2为当前层的节点数据,然后取出堆栈中2个元素[9, 20],此时s = [3, 1], 遍历结果为[[15, 7],[9, 20]];
+* 堆栈不空,获取栈顶元素1并出栈,1为当前层的节点数据,然后取出堆栈中1个元素[2],此时堆栈为空,遍历结果为[[15, 7],[9, 20], [3]];
+* 堆栈为空,返回遍历结果[[15, 7],[9, 20], [3]]; +### 2.2 代码 +```cpp +vector> levelOrderBottom(TreeNode* root) { + vector> res; + stack s; + //如果输入为空 + if (root == NULL) { + return res; + } + //1. 队列做BFS,右子树优先进队 + queue q; + q.push(root); + while( !q.empty() ){ + //获取当前层的数目 + int len = q.size(); + vector level; + TreeNode* tmp; + for( int i = 0; i < len; i++ ){ + //取一节点放入堆栈中 + tmp = q.front(); + q.pop(); + s.push(tmp->val); + //当前层所有的节点如果有孩子节点则压入队列 + //右子树优先入队 + if(tmp->right){ + q.push(tmp->right); + } + if(tmp->left){ + q.push(tmp->left); + } + } + //记录节点的个数 + s.push(len); + } + + //2. 遍历堆栈记录数据 + while( !s.empty() ){ + vector level_traverse; + int len = s.top(); + s.pop(); + for( int i = 0; i < len; i++ ){ + level_traverse.push_back(s.top()); + s.pop(); + } + res.push_back(level_traverse); + } + return res; + } +``` +## 3 思考与拓展 +### 3.1 思考 +本题的做法很多,我觉得基于队列+堆栈的做法的时间复杂度是最优的。 +#### 3.1.1 其他方法 +#### 3.1.1.1 队列BFS+反转 +1. 首先按照[102 二叉树的层次遍历](https://leetcode-cn.com/problems/binary-tree-level-order-traversal/)获取遍历结果res; +2. 反转 res;
+ +值得注意的是反转需要花费一定的时间。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +队列BFS+堆栈|O(2^h),h是二叉树的高度|O(n) +队列BFS+反转|O(2^h),h是二叉树的高度|O(n),个人觉得这种方法时间上稍弱于上者 +#### 3.1.3 难点分析 +1. 基于队列BFS+堆栈的方法对入队顺序有要求 +2. 基于队列BFS+堆栈的方法需要记录当前层的节点数据到堆栈中 +### 3.2 拓展 +如果让你做二叉树自底向上的锯齿形层次遍历呢? diff --git a/2018.12.10-leetcode107/Despacito.md b/2018.12.10-leetcode107/Despacito.md new file mode 100644 index 000000000..741d01485 --- /dev/null +++ b/2018.12.10-leetcode107/Despacito.md @@ -0,0 +1,59 @@ +# LeetCode 107 Binary Tree Level Order Traversal II +## 1. Description + +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] +] +``` + +## 2. Solution +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def levelOrderBottom(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + if root == None: + return [] + tmp = [root, '#'] + level = [] + result = [] + while len(tmp) > 1: + head = tmp.pop(0) + if head != '#': + level.append(head.val) + if head.left: + tmp.append(head.left) + if head.right: + tmp.append(head.right) + else: + tmp.append('#') + result.insert(0, level) + level = [] + result.insert(0, level) + return result +``` \ No newline at end of file diff --git a/2018.12.10-leetcode107/FFFro.md b/2018.12.10-leetcode107/FFFro.md new file mode 100644 index 000000000..b246f9407 --- /dev/null +++ b/2018.12.10-leetcode107/FFFro.md @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +import java.util.List; +import java.util.Stack; + +class Solution { + public List> levelOrderBottom(TreeNode root) { + List> list = new LinkedList<>(); + Stack> stack = new Stack<>(); + if (root == null) + return list; + levelOrderBottom(root,stack,0); + while (!stack.empty()) + list.add(stack.pop()); + return list; + } + + private void levelOrderBottom(TreeNode root, Stack> stack, int level) { + if (root == null){ + return; + } + if (stack.size() == level){ + List temp = new LinkedList<>(); + temp.add(root.val); + stack.push(temp); + }else { + stack.get(level).add(root.val); + } + levelOrderBottom(root.left,stack,level+1); + levelOrderBottom(root.right,stack,level+1); + } +} diff --git a/2018.12.10-leetcode107/GatesMa.md b/2018.12.10-leetcode107/GatesMa.md new file mode 100644 index 000000000..8f64b0c3c --- /dev/null +++ b/2018.12.10-leetcode107/GatesMa.md @@ -0,0 +1,30 @@ +# c++ +```cpp +/** + * 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: + vector> res; + vector> levelOrderBottom(TreeNode* root) { + check(root, 0); + reverse(res.begin(), res.end()); + return res; + } + void check(TreeNode* root, int depth) { + if(root == NULL) return; + if(res.size() == depth) { + res.push_back(vector()); + } + res[depth].push_back(root->val); + check(root->left, depth+1); + check(root->right, depth+1); + } +}; +``` diff --git a/2018.12.10-leetcode107/Istoryforever.md b/2018.12.10-leetcode107/Istoryforever.md new file mode 100644 index 000000000..c942ff12e --- /dev/null +++ b/2018.12.10-leetcode107/Istoryforever.md @@ -0,0 +1,53 @@ +leetcode of 107 +``` +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +struct DNODE{ + int depth; + TreeNode * p; + DNODE(int d,TreeNode * p){ + this->depth = d; + this->p = p; + } +}; +class Solution { +public: + vector> levelOrderBottom(TreeNode* root) { + queue q; + DNODE dn(0,root); + q.push(dn); + int depth = 0; + vector>ans; + if(root == nullptr) return ans; + vectorcur; + while(!q.empty()){ + dn=q.front(); + q.pop(); + if(dn.p->left){ + q.push(DNODE(dn.depth+1,dn.p->left)); + } + if(dn.p->right){ + q.push(DNODE(dn.depth+1,dn.p->right)); + } + if(depth == dn.depth){ + cur.push_back(dn.p->val); + }else if(depth != dn.depth){ + ans.push_back(cur); + vector().swap(cur); + cur.push_back(dn.p->val); + depth = dn.depth; + } + } + ans.push_back(cur); + reverse(ans.begin(),ans.end()); + return ans; + } +}; +``` diff --git a/2018.12.10-leetcode107/MQQM.cpp b/2018.12.10-leetcode107/MQQM.cpp new file mode 100644 index 000000000..0ea285d22 --- /dev/null +++ b/2018.12.10-leetcode107/MQQM.cpp @@ -0,0 +1,49 @@ +/* + 题目: + 给定一个二叉树,返回其节点值自底向上的层次遍历。(即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) + + 做法:与第102题一样,返回前反转。 +*/ + +/** + * 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: + vector> levelOrderBottom(TreeNode* root) { + vector> rst; + if(root == NULL){ + return rst; + } + + queue que; + que.push(root); + while(!que.empty()){ + int len=que.size(); + + vector levelvec; + for(int i=0; ival); + + if(p->left != NULL){ + que.push(p->left); + } + if(p->right != NULL){ + que.push(p->right); + } + } + rst.push_back(levelvec); + } + + reverse(rst.begin(), rst.end());//反转rst + return rst; + } +}; diff --git a/2018.12.10-leetcode107/MQQM2.cpp b/2018.12.10-leetcode107/MQQM2.cpp new file mode 100644 index 000000000..0e4b222a3 --- /dev/null +++ b/2018.12.10-leetcode107/MQQM2.cpp @@ -0,0 +1,36 @@ +/* + 题目: + 给定一个二叉树,返回其节点值自底向上的层次遍历。(即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) + + 参考: + https://blog.csdn.net/Snow_Jie/article/details/80875360 +*/ + +/** + * 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: + vector> rst; + vector> levelOrderBottom(TreeNode* root) { + levelTra(root, 0); + return vector>(rst.rbegin(), rst.rend());//反向遍历rst,生成新的vector>容器对象 + } + void levelTra(TreeNode* root, int level){ + if(root == NULL){ + return; + } + if(level == rst.size()){ + rst.push_back(vector()); + } + rst[level].push_back(root->val); + levelTra(root->left, level+1); + levelTra(root->right, level+1); + } +}; diff --git a/2018.12.10-leetcode107/Ostrichcrab.md b/2018.12.10-leetcode107/Ostrichcrab.md new file mode 100644 index 000000000..1bc82641f --- /dev/null +++ b/2018.12.10-leetcode107/Ostrichcrab.md @@ -0,0 +1,34 @@ +``` +/** + * 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: + vector> levelOrderBottom(TreeNode* root) { + queue que; + vector > result; + if(root == NULL) return result; + que.push(root); + while(!que.empty()){ + int size = que.size(); + vector tmp; + for(int i = 0; i < size; i++){ + TreeNode* t = que.front(); + if(t->left) que.push(t->left); + if(t->right) que.push(t->right); + tmp.push_back(t->val); + que.pop(); + } + result.push_back(tmp); + } + reverse(result.begin(),result.end()); + return result; + } +}; +``` diff --git a/2018.12.10-leetcode107/Sagittarius.md b/2018.12.10-leetcode107/Sagittarius.md new file mode 100644 index 000000000..b8a6cf756 --- /dev/null +++ b/2018.12.10-leetcode107/Sagittarius.md @@ -0,0 +1,45 @@ +``` +/** + * 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: + vector> a; + vector> levelOrderBottom(TreeNode* root) { + if(!root) + return a; + + lot(root,0); + for(int i=0;i v1; + v1=a[i]; + a[i]=a[a.size()-1-i]; + a[a.size()-1-i]=v1; + } + return a; + } + void lot(TreeNode* node,int level) + { + if(a.size() v1; + v1.push_back(node->val); + a.push_back(v1); + } + else + a[level].push_back(node->val); + + if(node->left) + lot(node->left,level+1); + if(node->right) + lot(node->right,level+1); + } +}; +``` diff --git a/2018.12.10-leetcode107/Sunny.md b/2018.12.10-leetcode107/Sunny.md new file mode 100644 index 000000000..79cc3328f --- /dev/null +++ b/2018.12.10-leetcode107/Sunny.md @@ -0,0 +1,22 @@ +```java +class Solution { + + private List> result = new ArrayList<>(); + + public List> levelOrderBottom(TreeNode root) { + levelOrderBottom(root, 0); + return result; + } + + public void levelOrderBottom(TreeNode node, int level) { + if (node != null) { + if (result.size() <= level) { + result.add(0, new ArrayList<>()); + } + result.get(result.size() - 1 - level).add(node.val); + levelOrderBottom(node.left, level+1); + levelOrderBottom(node.right, level+1); + } + } +} +``` diff --git a/2018.12.10-leetcode107/TheRocket.md b/2018.12.10-leetcode107/TheRocket.md new file mode 100644 index 000000000..c67e38286 --- /dev/null +++ b/2018.12.10-leetcode107/TheRocket.md @@ -0,0 +1,37 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrderBottom(TreeNode root) { + LinkedList> res = new LinkedList<>(); + Queue queue = new LinkedList<>(); + if (root != null) { + queue.offer(root); + } + while (!queue.isEmpty()) { + int size = queue.size(); + // 用来存储这一层结点的链表 + List level = new LinkedList<>(); + while (size-- != 0) { + TreeNode node = queue.poll(); + level.add(node.val); + if (node.left != null) { + queue.offer(node.left); + } + if (node.right != null) { + queue.offer(node.right); + } + } + res.addFirst(level); + } + return res; + } +} +``` diff --git a/2018.12.10-leetcode107/Tony the Cyclist.md b/2018.12.10-leetcode107/Tony the Cyclist.md new file mode 100644 index 000000000..43c225747 --- /dev/null +++ b/2018.12.10-leetcode107/Tony the Cyclist.md @@ -0,0 +1,43 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +import java.util.*; +class Solution { + public List> levelOrderBottom(TreeNode root) { + ArrayDeque d = new ArrayDeque<>(); + List> lists = new ArrayList<>(); + List tmp = new ArrayList<>(); + if (root == null){ + return lists; + } + d.addFirst(root); + int length = d.size(); + while (!d.isEmpty()){ + TreeNode node = d.pollLast(); + tmp.add(node.val); + length --; + if (node.left != null){ + d.addFirst(node.left); + } + if (node.right != null){ + d.addFirst(node.right); + } + if (length == 0){ + lists.add(new ArrayList<>(tmp)); + length = d.size(); + tmp.clear(); + + } + } + Collections.reverse(lists); + return lists; + } +} +``` diff --git a/2018.12.10-leetcode107/WhiteNight.md b/2018.12.10-leetcode107/WhiteNight.md new file mode 100644 index 000000000..09e8c40dd --- /dev/null +++ b/2018.12.10-leetcode107/WhiteNight.md @@ -0,0 +1,69 @@ +```java +import java.util.*; + +/** + * 二叉树的层次遍历2 + *给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) + * + */ +public class Tree11 +{ + public static class TreeNode { + int data; + TreeNode left; + TreeNode right; + + TreeNode(int val) { + data = val; + } + } + + public List> levelOrderBottom(TreeNode root) { + List> list = new ArrayList<>(); + Queue queue = new LinkedList<>(); + Stack> stack = new Stack<>(); + + if (root != null) { + queue.offer(root); + } + + while (!queue.isEmpty()) { + //temp初始化要放在此处,每次循环之后要置空 + List temp = new ArrayList<>(); + int level = queue.size(); + + for (int i = 0; i < level; i++) { + if (queue.peek().left != null) + queue.offer(queue.peek().left); + + if (queue.peek().right != null) + queue.offer(queue.peek().right); + + temp.add(queue.poll().data); + } + stack.push(temp); + } + + while (!stack.isEmpty()) { + list.add(stack.pop()); + } + + return list; + } + + public static void main(String[] args) { + TreeNode p = new TreeNode(4); + p.left = new TreeNode(9); + p.right = new TreeNode(20); + p.right.left = new TreeNode(15); + p.right.right = new TreeNode(7); + + Tree11 t = new Tree11(); + List> list= t.levelOrderBottom(p); + + for (int i = 0; i < list.size(); i++) { + System.out.print(list.get(i) + " "); + } + } +} +``` \ No newline at end of file diff --git a/2018.12.10-leetcode107/fish.md b/2018.12.10-leetcode107/fish.md new file mode 100644 index 000000000..d22ca2d06 --- /dev/null +++ b/2018.12.10-leetcode107/fish.md @@ -0,0 +1,59 @@ +``` +public class Solution { + private static LinkedList> result = new LinkedList<>(); + + public static void traversalBinaryTree(TreeNode node) { + if (node != null) { + List list = new ArrayList<>(node.getVal()); + list.add(node.getVal()); + result.addFirst(list); + + TreeNode left = node.getLeft(); + TreeNode right = node.getRight(); + traversalBinaryTree(left, 1); + traversalBinaryTree(right, 1); + } + } + + public static void traversalBinaryTree(TreeNode node, int level) { + if (node != null) { + List list; + if (result.size() == level) { + list = new ArrayList<>(); + result.addFirst(list); + }else { + list = result.get(result.size() - 1- level); + } + list.add(node.getVal()); + + TreeNode left = node.getLeft(); + TreeNode right = node.getRight(); + + traversalBinaryTree(left, level + 1); + traversalBinaryTree(right, level + 1); + } + } + + public static void main(String[] args) { + TreeNode r3r = new TreeNode(7, null, null); + TreeNode r3l = new TreeNode(15, null, null); + +// TreeNode l3r = new TreeNode(18, null, null); +// TreeNode l3l = new TreeNode(22, null, null); + + TreeNode l2r = new TreeNode(20, r3l, r3r); + TreeNode l2l = new TreeNode(9, null, null); + TreeNode root = new TreeNode(3, l2l, l2r); + traversalBinaryTree(root); + System.out.println(result); + } +} + +@Data +@AllArgsConstructor +@NoArgsConstructor +@ToString +class TreeNode { + private int val; + private TreeNode left; + private TreeNode right; diff --git a/2018.12.10-leetcode107/marguerite.md b/2018.12.10-leetcode107/marguerite.md new file mode 100644 index 000000000..7206c9bfb --- /dev/null +++ b/2018.12.10-leetcode107/marguerite.md @@ -0,0 +1,60 @@ +###107. Binary Tree Level Order Traversal + +###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,#,#,15,7}, + +### 3 + / \ + 9 20 + / \ + 15 7 + +###return its bottom-up level order traversal as: +[ + [15,7], + [9,20], + [3] +] + +``` + public List> levelOrderBottom(TreeNode root) { + LinkedList> result = new LinkedList>(); + + if (root == null) { + return result; + } + Queue queue = new LinkedList(); + queue.add(root); + int i = queue.size(); // 记录每层的结点个数 + TreeNode tempNode = null; + List singleLevel = new ArrayList<>(); + while (!queue.isEmpty()) { + if (i == 0) {// 一层记录结束 + // + result.addFirst(singleLevel); + + i = queue.size(); + singleLevel = new ArrayList<>(); + } + tempNode = queue.poll(); + singleLevel.add(tempNode.val); + + --i; + + if (tempNode.left != null) { + queue.add(tempNode.left); + } + if (tempNode.right != null) { + queue.add(tempNode.right); + } + + } + result.addFirst(singleLevel); + return result; + } +``` diff --git a/2018.12.10-leetcode107/sourcema.md b/2018.12.10-leetcode107/sourcema.md new file mode 100644 index 000000000..476adcfa8 --- /dev/null +++ b/2018.12.10-leetcode107/sourcema.md @@ -0,0 +1,32 @@ +# leetcode 107 + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + class Solution { + public List> levelOrderBottom(TreeNode root) { + List> lists = new ArrayList<>(); + if (root == null) { + return lists; + } + dfs(lists, root, 0); + Collections.reverse(lists); + return lists; + } + private static void dfs(List> lists, TreeNode root, int level) { + if (root == null) { + return; + } + if (lists.size() < level + 1) { + lists.add(new ArrayList()); + } + lists.get(level).add(root.val); + dfs(lists,root.left,level+1); + dfs(lists,root.right,level+1); + } + } diff --git a/2018.12.10-leetcode107/syuan.md b/2018.12.10-leetcode107/syuan.md new file mode 100644 index 000000000..81742163d --- /dev/null +++ b/2018.12.10-leetcode107/syuan.md @@ -0,0 +1,97 @@ +##### 题目 + +``` +给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) + +例如: +给定二叉树 [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 + +返回其自底向上的层次遍历为: + +[ + [15,7], + [9,20], + [3] +] +``` +##### 递归 + +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrderBottom(TreeNode root) { + List> res=new ArrayList<>(); + if (root==null) { + return res; + } + levelOrderBottomHelper(res,root,0); + return res; + } + + public void levelOrderBottomHelper(List> list,TreeNode node,int level){ + if (node==null) { + return; + } + if (list.size()<=level) { + list.add(0,new ArrayList()); + } + list.get(list.size()-level-1).add(node.val); + levelOrderBottomHelper(list,node.left,level+1); + levelOrderBottomHelper(list,node.right,level+1); + + } +} +``` +##### 非递归 + +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrderBottom(TreeNode root) { + List> resList=new ArrayList<>(); + Queue queue=new LinkedList<>(); + if (root==null) { + return resList; + } + + queue.offer(root); + while(!queue.isEmpty()){ + int length=queue.size(); + List tempList=new ArrayList<>(); + for (int i=0; i> levelOrderBottom(TreeNode root) { + LinkedList> res = new LinkedList<>(); + LinkedList queue = new LinkedList<>(); + if(root == null) return res; + TreeNode p = root; + queue.add(root); + while(!queue.isEmpty()) { + int size = queue.size(); + List list = new ArrayList<>(); + for (int i = 0; i < size; i++) { + p = queue.remove(); + if(p.left != null) queue.add(p.left); + if(p.right != null) queue.add(p.right); + list.add(p.val); + } + res.add(0, list); + } + return res; + } +} diff --git "a/2018.12.10-leetcode107/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.10-leetcode107/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..e74688569 --- /dev/null +++ "b/2018.12.10-leetcode107/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,43 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrderBottom(TreeNode root) { + List> res = new ArrayList<>(); + if(root==null)return res; + List tmp = new ArrayList<>(); + Queue q = new LinkedList<>(); + q.add(root); + int next=0; + int left=1; + while(!q.isEmpty()){ + TreeNode r = q.poll(); + tmp.add(r.val); + left--; + if(r.left!=null){ + q.add(r.left); + next++; + } + if(r.right!=null){ + q.add(r.right); + next++; + } + if(left==0){ + res.add(0,tmp); + tmp = new ArrayList<>(); + left=next; + next=0; + } + } + //Collections.reverse(res); + return res; + } +} +``` diff --git "a/2018.12.10-leetcode107/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.12.10-leetcode107/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..de688e41c --- /dev/null +++ "b/2018.12.10-leetcode107/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,61 @@ +``` +/** +给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) + +例如: +给定二叉树 [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回其自底向上的层次遍历为: + +[ + [15,7], + [9,20], + [3] +] + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrderBottom(TreeNode root) { + List> res =new ArrayList<>(); + Stack> stk=new Stack<>(); + if(root==null){ + return res; + } + Queue queue=new LinkedList(); + queue.add(root); + TreeNode node=null; + while(!queue.isEmpty()){ + int width=queue.size();//队列的大小就是每一层的宽度 + List list=new ArrayList<>(); + while(width>0){ //按照层的宽度来遍历,每次存放在list中的是当前层从左往右的数字,如果该数字下有子树,则将子树节点存放到队列中,作为下一 // 层的要遍历的数字。 + node=queue.poll(); + list.add(node.val); + if(node.left!=null ) + queue.add(node.left); + if(node.right!=null) + queue.add(node.right); + width--; + } + stk.push(list); + //res.add(list); + } + + while(!stk.isEmpty()){ + res.add(stk.pop()); + } + + return res; + } +} +``` diff --git "a/2018.12.10-leetcode107/\345\246\256\345\217\257.md" "b/2018.12.10-leetcode107/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..bb7baf65b --- /dev/null +++ "b/2018.12.10-leetcode107/\345\246\256\345\217\257.md" @@ -0,0 +1,107 @@ +```java +package sy181210; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + + + +/** + * @author suyuan + * + 给定一个二叉树,返回其节点值自底向上的层次遍历。 + (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) + +例如: +给定二叉树 [3,9,20,null,null,15,7], + + 3 + / \ + 9 20 + / \ + 15 7 +返回其自底向上的层次遍历为: + +[ + [15,7], + [9,20], + [3] +] + */ +public class leetcode_107二叉树的层次遍历_II +{ + + public static void main(String[] args) + { + TreeNode node1=new TreeNode(3); + TreeNode node2=new TreeNode(9); + TreeNode node3=new TreeNode(20); + TreeNode node4=new TreeNode(15); + TreeNode node5=new TreeNode(7); + + node1.left=node2; + node1.right=node3; + + node2.left=node4; + node2.right=node5; + + node3.left=null; + node3.right=null; + + node4.left=null; + node4.right=null; + node5.left=null; + node5.right=null; + +// List> resList=levelOrder(node1); + List> resList=levelOrderBottom(node1); + for (List list : resList) + { + for (Integer integer : list) + { + System.out.print(integer+" "); + } + System.out.println(); + } + + + } + + public static List> levelOrderBottom(TreeNode root) + { + List> result=new ArrayList>(); + if(root==null) + return result; + Queue queue=new LinkedList(); + queue.add(root); + TreeNode node=null; + + while(!queue.isEmpty()) + { + //高度还是要记的...省不了 + int count=queue.size(); + List list=new ArrayList<>(); + while(count>0) + { + node=queue.poll(); + list.add(node.val); + if(node.left!=null ) + queue.add(node.left); + if(node.right!=null) + queue.add(node.right); + count--; + } + + //result.add(list); + result.add(0,list);//...一口老血,这么每次都把最后的作为最新的加进来 + } + // Collections.reverse(result); 这是在原来的基础上反转,没上面那个快 这个3ms + + return result; + } + +} +``` diff --git "a/2018.12.10-leetcode107/\345\274\240\345\260\217\350\203\226.md" "b/2018.12.10-leetcode107/\345\274\240\345\260\217\350\203\226.md" new file mode 100644 index 000000000..ae04aa3de --- /dev/null +++ "b/2018.12.10-leetcode107/\345\274\240\345\260\217\350\203\226.md" @@ -0,0 +1,24 @@ + /** + * 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: + vector> levelOrderBottom(TreeNode* root) { + vector> array; + levelorder(root, 0,array); + return vector> (array.rbegin(), array.rend()); + } + void levelorder(TreeNode *root, int level, vector > &array) { + if (root==nullptr) return; + if (array.size() == level) array.push_back({}); + array[level].push_back(root->val); + if (root->left) levelorder(root->left, level + 1, array); + if (root->right) levelorder(root->right, level + 1, array); + } + }; diff --git "a/2018.12.10-leetcode107/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.10-leetcode107/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..65f9a443d --- /dev/null +++ "b/2018.12.10-leetcode107/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,40 @@ +#### [107. Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/) +**题目描述** +> 给定二叉树,返回自底向上的层次遍历结果(从左向右,逐层从叶子节点到根节点) + +**例子** +> 略 + +**思想** +Easy。和层次遍历区别: +反转res - res[::-1] 或插入时res.insert(0, row)/res = [row] + res + +**解法** +```python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def levelOrderBottom(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + res = [] + queue = [root] + while queue and root: + row = [] + for _ in range(len(queue)): + node = queue.pop(0) + row.append(node.val) + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + res.insert(0, row) + return res +``` \ No newline at end of file diff --git "a/2018.12.10-leetcode107/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.10-leetcode107/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..598d1b371 --- /dev/null +++ "b/2018.12.10-leetcode107/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,54 @@ +``` +/** + * 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: + vector> levelOrderBottom(TreeNode* root) { + vector> v; + if (!root) + { + return v; + } + + queue q; + q.push(root); + int len=1; + TreeNode *node = root; + + while (!q.empty()) + { + vector vi; + int size = 0; + for (int i=0; ileft) + { + size++; + q.push(tmp->left); + } + + if (tmp->right) + { + size++; + q.push(tmp->right); + } + vi.push_back(tmp->val); + q.pop(); + } + + v.insert(v.begin(),vi); + len = size; + } + + return v; + } +}; +``` diff --git "a/2018.12.10-leetcode107/\350\216\216\350\216\216.md" "b/2018.12.10-leetcode107/\350\216\216\350\216\216.md" new file mode 100644 index 000000000..df88cd83b --- /dev/null +++ "b/2018.12.10-leetcode107/\350\216\216\350\216\216.md" @@ -0,0 +1,25 @@ +``` +class Solution: + def levelOrderBottom(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + q = [root] + v = [] + if not root: + return [] + while q: + templist = [] + templen = len(q) + for i in range(templen): + temp = q.pop(0) + templist.append(temp.val) + if temp.left: + q.append(temp.left) + if temp.right: + q.append(temp.right) + v.append(templist) + v.reverse() + return v +``` diff --git "a/2018.12.10-leetcode107/\351\230\263.md" "b/2018.12.10-leetcode107/\351\230\263.md" new file mode 100644 index 000000000..f37921d51 --- /dev/null +++ "b/2018.12.10-leetcode107/\351\230\263.md" @@ -0,0 +1,29 @@ +public List> levelOrderBottom(TreeNode root) { + List> list = new LinkedList>(); + Stack> stack = new Stack>(); + if(root == null) { + return list; + } + Queue queue = new LinkedList(); + queue.add(root); + + while(!queue.isEmpty()) { + List sublist = new LinkedList(); + int size = queue.size(); + for(int i = 0; i < size; i++) { + TreeNode currentNode = queue.poll(); + sublist.add(currentNode.val); + if(currentNode.left != null) { + queue.add(currentNode.left); + } + if(currentNode.right != null) { + queue.add(currentNode.right); + } + } + stack.push(sublist); + } + while(!stack.isEmpty()) { + list.add(stack.pop()); + } + return list; + } diff --git "a/2018.12.11-leetcode108/108. \345\260\206\346\234\211\345\272\217\346\225\260\347\273\204\350\275\254\346\215\242\344\270\272\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221.md" "b/2018.12.11-leetcode108/108. \345\260\206\346\234\211\345\272\217\346\225\260\347\273\204\350\275\254\346\215\242\344\270\272\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221.md" new file mode 100644 index 000000000..209e3ef4b --- /dev/null +++ "b/2018.12.11-leetcode108/108. \345\260\206\346\234\211\345\272\217\346\225\260\347\273\204\350\275\254\346\215\242\344\270\272\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221.md" @@ -0,0 +1 @@ +20 diff --git a/2018.12.11-leetcode108/Avalon.md b/2018.12.11-leetcode108/Avalon.md new file mode 100644 index 000000000..a19b40e26 --- /dev/null +++ b/2018.12.11-leetcode108/Avalon.md @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + if (nums == null || nums.length == 0) return null; + return buildAVLTree(nums, 0, nums.length - 1); + } + private static TreeNode buildAVLTree(int[] nums, int start, int end) { + if (start > end) return null; + if (start == end) return new TreeNode(nums[start]); + int mid = (start + end) / 2; + TreeNode node = new TreeNode(nums[mid]); + node.left = buildAVLTree(nums, start, mid - 1); + node.right = buildAVLTree(nums, mid + 1, end); + return node; + } +} diff --git a/2018.12.11-leetcode108/Be a fresh man.md b/2018.12.11-leetcode108/Be a fresh man.md new file mode 100644 index 000000000..d2dafa73f --- /dev/null +++ b/2018.12.11-leetcode108/Be a fresh man.md @@ -0,0 +1,88 @@ +## 108_(将有序数组转换为二叉搜索树)Convert Sorted Array to Binary Search Tree +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
+本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 +### 1.2 输入与输出 +输入: +* vector< int>& nums:按照升序排列的有序数组的引用
+输出:
+* TreeNode*:高度平衡二叉搜索树的根节点指针 + +### 1.3 样例 +#### 1.3.1 样例1
+输入:
+有序数组:[-10,-3,0,5,9]
+输出:
+一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
+ + 0 + / \ + -3 9 + / / + -10 5 + +## 2 思路描述与代码 +### 2.1 思路描述(递归) +1. 以数组的中间节点为二叉搜索树的根节点,中间节点的左部分为左二叉搜索子树,中间节点的右部分为右二叉搜索子树。 +2. 以根节点左右递归即可。 + +比如给定有序数组:[-10,-3,0,5,9]
+先获取根节点 *root 的值0
+递归左子树root->left = sortedArrayToBST([-10, -3]), root->right = sortedArrayToBST([5, 9]])
+根据同样的方法可以获取 root 左右二叉搜索子树,结果分别是: + + -3 9 + / / + -10 5 + +于是构造出的二叉搜索树是: + + 0 + / \ + -3 9 + / / + -10 5 + +### 2.2 代码 +```cpp +//涉及的概念 +//vector 可以理解为一个长度可变的 int 数组 +//vector::iterator 可以理解为长度可变的 int 数组的指针 +//TreeNode* root = new TreeNode(val) root 是从堆中生成一个值为 val 的链表节点的指针 +//root->left 是 root 所指向节点的左子树根节点的指针, root->right 同理 + +typedef vector::iterator iter; +public: +//采用递归的思路 +TreeNode* sortedArrayToBST(vector& nums) { + return sortedArrayToBST_recurse(nums.begin(), nums.size()); +} +//采用递归的思路 +TreeNode* sortedArrayToBST_recurse(iter begin, int len){ + //边界情况 + if(len == 0) return nullptr; + if(len == 1) return new TreeNode(*begin); + //找到根节点,然后左右递归 + //左子树长度为 len / 2 + //右子树长度是 len - len / 2 - 1 + TreeNode* root = new TreeNode(*(begin + len / 2)); + root->left = sortedArrayToBST_recurse(begin, len / 2); + root->right = sortedArrayToBST_recurse(begin + len / 2 + 1, len - len / 2 - 1); + return root; +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题数据是基于数组的结构,array[len / 2]即是根节点,然后左右递归即可。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +递归|O(n)|O(n) +#### 3.1.3 难点分析 +1. 边界的判断 + +### 3.2 拓展 +如果给定的数据是链表呢?会影响时间复杂度吗? diff --git a/2018.12.11-leetcode108/FFFro.md b/2018.12.11-leetcode108/FFFro.md new file mode 100644 index 000000000..63c82b103 --- /dev/null +++ b/2018.12.11-leetcode108/FFFro.md @@ -0,0 +1,19 @@ +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + if (nums.length == 0) + return null; + return build(nums,0,nums.length - 1); + } + + private TreeNode build(int[] nums, int start, int end) { + if (start > end) + return null; + if (start == end) + return new TreeNode(nums[start]); + int mid = start + (end - start) / 2; + TreeNode root = new TreeNode(nums[mid]); + root.left = build(nums,start,mid-1); + root.right = build(nums,mid+1,end); + return root; + } +} diff --git a/2018.12.11-leetcode108/GatesMa.md b/2018.12.11-leetcode108/GatesMa.md new file mode 100644 index 000000000..64adddba5 --- /dev/null +++ b/2018.12.11-leetcode108/GatesMa.md @@ -0,0 +1,27 @@ +# c++ +```cpp +/** + * 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& nums) { + if(nums.size() == 0) return NULL; + return buildTree(nums, 0, nums.size()-1); + } + TreeNode* buildTree(vector& nums,int n_l, int n_r) { + if(n_l > n_r) return NULL; + int mid = (n_l + n_r) / 2; + TreeNode* node = new TreeNode(nums[mid]); + node->left = buildTree(nums, n_l, mid-1); + node->right = buildTree(nums, mid+1, n_r); + return node; + } +}; +``` diff --git a/2018.12.11-leetcode108/Istoryforever.md b/2018.12.11-leetcode108/Istoryforever.md new file mode 100644 index 000000000..ea86984d0 --- /dev/null +++ b/2018.12.11-leetcode108/Istoryforever.md @@ -0,0 +1,71 @@ +leetcode of 108 +``` +/** + * 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 { + int depth(TreeNode * root){ + if(root == nullptr) return 0; + return max(depth(root->left),depth(root->right))+1; + } + void fix(TreeNode * root){ + int leftd = depth(root->left); + int rightd = depth(root->right); + if(rightd - leftd > 1){ + //执行左旋 + TreeNode *parent =new TreeNode(0) ; + *parent = *root; + TreeNode * cur = root->right; + TreeNode * left= root->right->left; + * root = * cur; + parent->right = root->left; + root->left = parent; + delete cur; + } + if(leftd - rightd > 1){ + //执行右旋 + TreeNode *parent =new TreeNode(0) ; + *parent = *root; + TreeNode * cur = root->left; + TreeNode * right = cur->right; + *root = *cur; + parent->left = right; + root->right = parent; + delete cur; + } + } + void insert(TreeNode * &root,int val){ + if(root == nullptr){ + root = new TreeNode(val); + return; + } + if(root->val < val){ + if(root->right) + insert(root->right,val); + else + root->right = new TreeNode(val); + }else{ + if(root->left) + insert(root->left,val); + else + root->left = new TreeNode(val); + } + fix(root); + } + +public: + TreeNode* sortedArrayToBST(vector& nums) { + TreeNode * root = nullptr; + for(auto i : nums){ + insert(root,i); + } + return root; + } +}; +``` diff --git a/2018.12.11-leetcode108/MQQM.cpp b/2018.12.11-leetcode108/MQQM.cpp new file mode 100644 index 000000000..d20b87fd9 --- /dev/null +++ b/2018.12.11-leetcode108/MQQM.cpp @@ -0,0 +1,39 @@ +/* + 题目: + 将一个按照升序排列的有序数组,转换为一棵高度平衡的二叉搜索树。 + 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 + + 做法: + 因为是升序排列的数组,所以可以取区间内最中间的元素生成根节点,左子树为前半部分元素,右子树为后半部分元素。 + + 参考: + https://www.cnblogs.com/liez/p/5304562.html +*/ + +/** + * 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& nums) { + return createBST(nums, 0, nums.size()-1); + } + TreeNode* createBST(vector& nums, int left, int right){ + if(left>right){ + return NULL; + } + + int mid=(left+right)/2; + TreeNode* root = new TreeNode(nums[mid]); + root->left=createBST(nums, left, mid-1); + root->right=createBST(nums, mid+1, right); + + return root; + } +}; diff --git a/2018.12.11-leetcode108/Ostrichcrab.md b/2018.12.11-leetcode108/Ostrichcrab.md new file mode 100644 index 000000000..c170b2039 --- /dev/null +++ b/2018.12.11-leetcode108/Ostrichcrab.md @@ -0,0 +1,23 @@ +``` +/** + * 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& nums) { + if(nums.size()==0) return NULL; + TreeNode* root = new TreeNode(nums[nums.size()/2]); + vector nums_left = vector(nums.begin(),nums.begin()+nums.size()/2); + vector nums_right = vector(nums.begin()+nums.size()/2+1,nums.end()); + root->left = sortedArrayToBST(nums_left); + root->right = sortedArrayToBST(nums_right); + return root; + } +}; +``` diff --git a/2018.12.11-leetcode108/Sagittarius.md b/2018.12.11-leetcode108/Sagittarius.md new file mode 100644 index 000000000..332a38179 --- /dev/null +++ b/2018.12.11-leetcode108/Sagittarius.md @@ -0,0 +1,29 @@ +``` +/** + * 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& nums) { + return buildBST(0,nums.size()-1,nums); + } + + TreeNode* buildBST(int l,int r,vector& nums) + { + if(l>r) + return nullptr; + int k=l+(r-l+1)/2; + TreeNode* root=new TreeNode(nums[k]); + root->left=buildBST(l,k-1,nums); + root->right=buildBST(k+1,r,nums); + return root; + + } +}; +``` diff --git a/2018.12.11-leetcode108/Sunny.md b/2018.12.11-leetcode108/Sunny.md new file mode 100644 index 000000000..af746c9fb --- /dev/null +++ b/2018.12.11-leetcode108/Sunny.md @@ -0,0 +1,17 @@ +```java +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + if (nums == null || nums.length == 0) + return null; + int i = nums.length / 2; + TreeNode node = new TreeNode(nums[i]); + if (i > 0) { + node.left = sortedArrayToBST(Arrays.copyOfRange(nums, 0, i)); + if (i+1 < nums.length) { + node.right = sortedArrayToBST(Arrays.copyOfRange(nums, i+1, nums.length)); + } + } + return node; + } +} +``` diff --git a/2018.12.11-leetcode108/TheRocket.md b/2018.12.11-leetcode108/TheRocket.md new file mode 100644 index 000000000..084e64087 --- /dev/null +++ b/2018.12.11-leetcode108/TheRocket.md @@ -0,0 +1,30 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + if (nums == null || nums.length == 0) { + return null; + } + return sortedArrayToBST(nums, 0, nums.length - 1); + } + + private TreeNode sortedArrayToBST(int[] nums, int lo, int hi) { + if (lo > hi) { + return null; + } + int mid = lo + (hi - lo) / 2; + TreeNode root = new TreeNode(nums[mid]); + root.left = sortedArrayToBST(nums, lo, mid - 1); + root.right = sortedArrayToBST(nums, mid + 1, hi); + return root; + } +} +``` diff --git a/2018.12.11-leetcode108/WhiteNight.md b/2018.12.11-leetcode108/WhiteNight.md new file mode 100644 index 000000000..5c13d5fa0 --- /dev/null +++ b/2018.12.11-leetcode108/WhiteNight.md @@ -0,0 +1,65 @@ +```java +/** + *将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。 + * + *本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 + * + */ +public class Tree3 +{ + public static class TreeNode + { + int data; + TreeNode left; + TreeNode right; + TreeNode(int val) + { + data = val; + } + } + + public TreeNode sortedArrayToBST(int[] nums) + { + if (nums.length == 0) + return null; + else + return buildBST(nums,0,nums.length - 1); + } + + private TreeNode buildBST(int[] nums, int start, int end) + { + if (start <= end) + { + int mid = (start + end) / 2; + TreeNode root = new TreeNode(nums[mid]); + root.left = buildBST(nums, start, mid - 1); + root.right = buildBST(nums, mid + 1, end); + return root; + } + else + return null; + } + + //中序遍历验证结果 + public static void midPrint(TreeNode p) + { + if (p != null) + { + midPrint(p.left); + System.out.print(p.data + " "); + midPrint(p.right); + } + } + + public static void main(String[] args) + { + Tree3 t = new Tree3(); + int[] a = new int[]{-10,-3,0,5,9}; + + TreeNode p = t.sortedArrayToBST(a); + + midPrint(p); + } + +} +``` \ No newline at end of file diff --git a/2018.12.11-leetcode108/marguerite.md b/2018.12.11-leetcode108/marguerite.md new file mode 100644 index 000000000..e5b830943 --- /dev/null +++ b/2018.12.11-leetcode108/marguerite.md @@ -0,0 +1,52 @@ +LeetCode:108. 将有序数组转换为二叉搜索树(Java) + +####将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。 + +####本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 + +###给定有序数组: [-10,-3,0,5,9], + +####一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树: + + 0 + / \ + -3 9 + / / + + -10 5 + +####这个题有点类似二分查找,根节点在正中间,左子树的根节点在左边一半数组的正中间,右子树的根节点在右边一半数组的正中间;于是可以递归解决:先确定根节点,然后构造左子树,然后构造右子树, 结束条件类似二分查找(low > high)。 + +``` +/*** +definition for a binary tree node. +public class TreeNode{ + int val; + TreeNode left; + TreeNode right; + TreeNode(int x){val =x;} +} +**/ + +class Solution{ + public TreeNode sortedArrayToBST(int[] nums){ + if(nums == null){ + return null; + } + return convertTree(nums,0,nums.length-1); + } + + public TreeNode convertTree(int[] nums,int l,int r){//l:数组左边;r:数组右边,包括l和r + if(l<=r){ + int mid =(l+r)/2; + TreeNode newNode = new TreeNode(nums[mid]); + newNode.left = convertTree(nums,l,mid-1); + newNode.right = convertTree(nums,mid+1,r); + return newNode; + } + else{ + return null; + } + } +} +``` diff --git a/2018.12.11-leetcode108/sourcema.md b/2018.12.11-leetcode108/sourcema.md new file mode 100644 index 000000000..30cc95dcc --- /dev/null +++ b/2018.12.11-leetcode108/sourcema.md @@ -0,0 +1,29 @@ +# LeetCode 108 + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + class Solution { + public TreeNode sortedArrayToBST(int[] arr) { + if (arr.length == 0 || arr == null) { + return null; + } + TreeNode root=generate(arr, 0, arr.length - 1); + return root; + } + public TreeNode generate(int[] arr, int start, int end) { + if (start > end) { + return null; + } + int mid=(start+end)/2; + TreeNode head = new TreeNode(arr[mid]); + head.left = generate(arr, start, mid - 1); + head.right = generate(arr, mid + 1, end); + return head; + } + } diff --git "a/2018.12.11-leetcode108/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.11-leetcode108/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..1689dc7bd --- /dev/null +++ "b/2018.12.11-leetcode108/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,26 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + if(nums==null||nums.length==0)return null; + return sortToBST(nums,0,nums.length-1); + } + + TreeNode sortToBST(int[] nums,int l,int r){ + if(l>=nums.length||r<0||l>r)return null; + int mid = (l+r)/2; + TreeNode root = new TreeNode(nums[mid]); + root.left=sortToBST(nums,l,mid-1); + root.right=sortToBST(nums,mid+1,r); + return root; + } +} +``` diff --git "a/2018.12.11-leetcode108/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.12.11-leetcode108/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..66a062164 --- /dev/null +++ "b/2018.12.11-leetcode108/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,59 @@ +``` +/** +给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 + +本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 + +示例: + +给定的有序链表: [-10, -3, 0, 5, 9], + +一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: + + 0 + / \ + -3 9 + / / + -10 5 + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + if(head==null){ + return null; + } + return sortedListToBST(head,null); + } + public TreeNode sortedListToBST(ListNode head,ListNode end){ + if(head==end){ + return null; + } + ListNode fast=head; + ListNode slow=head; + while(fast!=end&&fast.next!=end){ + fast=fast.next.next; + slow=slow.next; + } + TreeNode node=new TreeNode(slow.val); + node.left=sortedListToBST(head,slow); + node.right=sortedListToBST(slow.next,end); + + return node; + } + +} +``` diff --git "a/2018.12.11-leetcode108/\345\246\256\345\217\257.md" "b/2018.12.11-leetcode108/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..af457999b --- /dev/null +++ "b/2018.12.11-leetcode108/\345\246\256\345\217\257.md" @@ -0,0 +1,95 @@ +```java +package sy181211; + + + +/** + * @author suyuan + * +将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。 + +本题中,一个高度平衡二叉树是指一个二叉树每个节点 +的左右两个子树的高度差的绝对值不超过 1。 + +示例: + +给定有序数组: [-10,-3,0,5,9], + +一个可能的答案是:[0,-3,9,-10,null,5], +它可以表示下面这个高度平衡二叉搜索树: + + 0 + / \ + -3 9 + / / + -10 5 + + 平衡二叉搜索树就是一个二分 + + */ +public class leetcode_108将有序数组转换为二叉搜索树 +{ + + public static void main(String[] args) + { + int[] arr=new int[]{-10,-3,0,5,9,13,14}; + TreeNode node=sortedArrayToBST(arr); + print(node); + + + } + + public static TreeNode sortedArrayToBST(int[] nums) + { + if(nums==null) + return null; + return sortedArrayToBST(nums, 0, nums.length-1); + } + + public static TreeNode sortedArrayToBST(int[] nums,int left,int right) + { + //二分 不能>= + if(left>right) + return null; + //相等返回左子树 写这句这个比我快 + else if(left==right) + return new TreeNode(nums[left]); + else + { + int mid=(left+right)/2; + TreeNode node=new TreeNode(nums[mid]); + node.left=sortedArrayToBST(nums, left, mid-1); + node.right=sortedArrayToBST(nums, mid+1, right); + return node; + } + } + + private static void print(TreeNode tree, int key, int direction) { + + if(tree != null) { + + if(direction==0) // tree是根节点 + System.out.printf("%2d is root\n", tree.val); + else // tree是分支节点 + System.out.printf("%2d is %2d's %6s child\n",tree.val,key, direction==1?"right" : "left"); + + print(tree.left, tree.val, -1); + print(tree.right,tree.val, 1); + } + } + + public static void print(TreeNode node) + { + if (node != null) + print(node, node.val, 0); + } + +} + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} +``` diff --git "a/2018.12.11-leetcode108/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.11-leetcode108/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..b4a147fb5 --- /dev/null +++ "b/2018.12.11-leetcode108/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,38 @@ +#### [108. Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/rotate-list/description/) + +**题目描述** +> 给定一升序排序的数组,将它转换成高度平衡的BST。 + +> 高度平衡的二叉树:每个结点两颗子树的深度差不超过1. + +**例子** +略 + +**思想** +看到树,想到递归方法求解。中间节点肯定是根节点,左侧都是左子树,右侧都是右子树。 + +**解法** +```python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def sortedArrayToBST(self, nums): + """ + :type nums: List[int] + :rtype: TreeNode + """ + if not nums: + return None + + n = len(nums) + root = TreeNode(nums[n//2]) + root.left = self.sortedArrayToBST(nums[:n//2]) + root.right = self.sortedArrayToBST(nums[n//2+1:]) + + return root +``` diff --git "a/2018.12.11-leetcode108/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.11-leetcode108/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..0d8389b88 --- /dev/null +++ "b/2018.12.11-leetcode108/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,32 @@ +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + if(nums.length==0||null==nums){ + return null; + }else{ + TreeNode root = generate(nums,0,nums.length-1); + return root; + } + } + + public TreeNode generate(int [] nums,int start,int end){ + if(start>end){ + return null; + } + int mid = (start+end)/2; + TreeNode head = new TreeNode(nums[mid]); + head.left = generate(nums,start,mid-1); + head.right = generate(nums,mid+1,end); + return head; + } +} +``` diff --git "a/2018.12.11-leetcode108/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.11-leetcode108/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..f41c646f0 --- /dev/null +++ "b/2018.12.11-leetcode108/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,28 @@ +``` +/** + * 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& nums) { + return build(nums, 0, nums.size()/2, nums.size()-1); + } + + TreeNode *build(vector& nums, int begin, int mid, int end) + { + if(begin > end) return NULL; + + TreeNode *root = new TreeNode(nums[mid]); + root->left = build(nums, begin, (begin+mid-1)/2, mid-1); + root->right = build(nums, mid+1, (mid+1+end)/2, end); + + return root; + } +}; +``` diff --git "a/2018.12.11-leetcode108/\350\216\216\350\216\216.md" "b/2018.12.11-leetcode108/\350\216\216\350\216\216.md" new file mode 100644 index 000000000..31d152f54 --- /dev/null +++ "b/2018.12.11-leetcode108/\350\216\216\350\216\216.md" @@ -0,0 +1,17 @@ +``` +class Solution: + def sortedArrayToBST(self, nums): + """ + :type nums: List[int] + :rtype: TreeNode + """ + if not nums: + return None + + n = len(nums)//2 + + root = TreeNode(nums[n]) + root.left = self.sortedArrayToBST(nums[:n]) + root.right = self.sortedArrayToBST(nums[n+1:]) + return root +``` diff --git "a/2018.12.12-leetcode109/109. \346\234\211\345\272\217\351\223\276\350\241\250\350\275\254\346\215\242\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221" "b/2018.12.12-leetcode109/109. \346\234\211\345\272\217\351\223\276\350\241\250\350\275\254\346\215\242\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221" new file mode 100644 index 000000000..6fae31ed1 --- /dev/null +++ "b/2018.12.12-leetcode109/109. \346\234\211\345\272\217\351\223\276\350\241\250\350\275\254\346\215\242\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221" @@ -0,0 +1,15 @@ +给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 + +本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 + +示例: + +给定的有序链表: [-10, -3, 0, 5, 9], + +一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: + + 0 + / \ + -3 9 + / / + -10 5 diff --git a/2018.12.12-leetcode109/Avalon.md b/2018.12.12-leetcode109/Avalon.md new file mode 100644 index 000000000..104062ea6 --- /dev/null +++ b/2018.12.12-leetcode109/Avalon.md @@ -0,0 +1,38 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + if (head==null)return null; + ListNode current = head; + List arr = new ArrayList<>(); + while (current !=null){ + arr.add(current.val); + current = current.next; + } + + return buildAVLTree(arr, 0, arr.size()-1); + } + private static TreeNode buildAVLTree(List list, int start, int end){ + if (start> end)return null; + int mid = (start+end)/2; + TreeNode node = new TreeNode(list.get(mid)); + node.left =buildAVLTree(list, start, mid-1); + node.right =buildAVLTree(list, mid+1, end); + return node; + } +} diff --git a/2018.12.12-leetcode109/Be a fresh man.md b/2018.12.12-leetcode109/Be a fresh man.md new file mode 100644 index 000000000..42f0f4523 --- /dev/null +++ b/2018.12.12-leetcode109/Be a fresh man.md @@ -0,0 +1,97 @@ +## 109_(有序链表转换为二叉搜索树)Convert Sorted List to Binary Search Tree +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
+本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 +### 1.2 输入与输出 +输入:
+* ListNode* head:有序链表的头节点指针
+输出:
+* output_type:TreeNode*:高度平衡二叉搜索树的根节点指针 +### 1.3 样例 +#### 1.3.1 样例1
+输入:
+给定的有序链表: [-10, -3, 0, 5, 9]
+输出:
+一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
+ + 0 + / \ + -3 9 + / / + -10 5 + + +## 2 思路描述与代码 +### 2.1 思路描述(快慢指针+递归) +1. 快慢指针分离成左子树所有节点构成的链表、根节点和右子树所有节点构成的链表 +2. 根据根节点递归分离的两个链表,第一个链表为左子树,第二个链表为右子树 + +比如给定的有序链表: [-10, -3, 0, 5, 9]
+先分离链表为list1 = [-10, -3], 根节点root的值 0, list2 = [5, 9];
+递归左子树root->left = sortedListToBST(list1), root->right = sortedListToBST(list2)
+根据同样的方法可以获取 root 左右二叉搜索子树分别是: + + -3 9 + / / + -10 5 + +于是构造出的二叉搜索树是: + + 0 + / \ + -3 9 + / / + -10 5 + +### 2.2 代码 +```cpp +//函数中涉及到的指针操作 +//head 为 ListNode* 类型的指针, head->val 是这个指针所指向的节点的值 +//head->next 为 head 所指向的节点的下一个节点的指针 + +//TreeNode* root = new TreeNode(val) 返回从堆中生成一个值为 val 的链表节点的指针给root +//root->left 是 root 所指向节点的左子树根节点的指针, root->right 同理 + +//解题思路 +//1.快慢指针分离成左子树所有节点构成的链表、根节点和右子树所有节点构成的链表 +//2.根据根节点递归分离的两个链表,第一个链表为左子树,第二个链表为右子树 +TreeNode* sortedListToBST(ListNode* head) { + //边界情况:链表为空或者只有一个节点 + if(head == nullptr) return nullptr; + if(head->next == nullptr) return new TreeNode(head->val); + + //1.快慢指针分离成根节点、左子树所有节点构成的链表和右子树所有节点构成的链表 + //slow为二叉搜索树左子树所有节点构成的链表的链表的尾巴,其链表头为head + //slow->next->val为二叉搜索树根节点的值 + //slow->next->next为二叉搜索树右子树所有节点构成的链表的头节点指针 + ListNode *slow = head, *fast = head->next; + while( fast != nullptr ){ + fast = fast->next == nullptr ? nullptr : fast->next->next; + slow = fast == nullptr ? slow : slow->next; + } + //2. 根据根节点递归分离的两个链表,第一个链表为左子树,第二个链表为右子树 + TreeNode* root = new TreeNode(slow->next->val); + slow->next = nullptr;//分离第一个链表 + ListNode* list2head = slow->next->next;//获取第二个链表的头节点指针 + //递归构造二叉搜索树 + root->left = sortedListToBST(head); + root->right = sortedListToBST(list2head); + return root; +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题数据是基于链表的结构,获取中间值相比于数组是要花很大的代价的,所以时间复杂度变大了。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +快慢指针+递归|O(n)|O(nlogn) +#### 3.1.3 难点分析 +1. 快慢指针分离链表 +2. 边界情况的考虑 + +### 3.2 拓展 +如果给定的链表不是有序的呢?会影响他的时间复杂度吗? diff --git a/2018.12.12-leetcode109/FFFro.md b/2018.12.12-leetcode109/FFFro.md new file mode 100644 index 000000000..b79a0d5fd --- /dev/null +++ b/2018.12.12-leetcode109/FFFro.md @@ -0,0 +1,20 @@ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + if (head == null) + return null; + if (head.next == null) + return new TreeNode(head.val); + ListNode fast = head.next; + ListNode slow = head; + while (fast != null){ + fast = fast.next == null ? null : fast.next.next; + slow = fast == null ? slow : slow.next; + } + TreeNode root = new TreeNode(slow.next.val); + ListNode right = slow.next.next; + slow.next = null; + root.left = sortedListToBST(head); + root.right = sortedListToBST(right); + return root; + } +} diff --git a/2018.12.12-leetcode109/GatesMa.md b/2018.12.12-leetcode109/GatesMa.md new file mode 100644 index 000000000..f460b1088 --- /dev/null +++ b/2018.12.12-leetcode109/GatesMa.md @@ -0,0 +1,40 @@ +# c++ +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +/** + * 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* sortedListToBST(ListNode* head) { + if(head == nullptr) return nullptr; + return buildTree(head, nullptr); + } + TreeNode* buildTree(ListNode* head, ListNode* end) { + if(head == end) return nullptr; + ListNode* slow = head; + ListNode* fast = head; + while(fast != end && fast->next != end) { + slow = slow->next; + fast = fast->next->next; + } + TreeNode* node = new TreeNode(slow->val); + node->left = buildTree(head, slow); + node->right = buildTree(slow->next, end); + return node; + } +}; +``` diff --git a/2018.12.12-leetcode109/Istoryforever.md b/2018.12.12-leetcode109/Istoryforever.md new file mode 100644 index 000000000..69579adc2 --- /dev/null +++ b/2018.12.12-leetcode109/Istoryforever.md @@ -0,0 +1,49 @@ +leetcode of 109 +``` +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +/** + * 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: + ListNode * getHalfListNode(ListNode *head){ + ListNode * p1,*p2; + ListNode * d= new ListNode(-1); + d->next = head; + p1 = d; + p2 = head; + while(p2 && p2->next){ + p2 = p2->next->next; + p1 = p1->next; + } + delete d; + return p1; + } + TreeNode* sortedListToBST(ListNode* head) { + if(head == nullptr) return nullptr; + if(head->next == nullptr) return new TreeNode(head->val); + ListNode * split = getHalfListNode(head); + ListNode * cur = split->next; + TreeNode * root = new TreeNode (cur->val); + ListNode * right = cur->next; + split->next = nullptr; + root->left = sortedListToBST(head); + root->right = sortedListToBST(right); + return root; + + } +}; +``` diff --git a/2018.12.12-leetcode109/Ostrichcrab.md b/2018.12.12-leetcode109/Ostrichcrab.md new file mode 100644 index 000000000..d5df81813 --- /dev/null +++ b/2018.12.12-leetcode109/Ostrichcrab.md @@ -0,0 +1,46 @@ +``` +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +/** + * 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* work(vector nums){ + int size = nums.size(); + if(size==0) return NULL; + TreeNode* root = new TreeNode(nums[size/2]); + vector nums_left = vector(nums.begin(),nums.begin()+size/2); + vector nums_right = vector(nums.begin()+size/2+1,nums.end()); + root->left = work(nums_left); + root->right = work(nums_right); + return root; + } + TreeNode* sortedListToBST(ListNode* head) { + if(head==NULL) return NULL; + ListNode* t = head; + vector nums; + while(t->next){ + nums.push_back(t->val); + t = t->next; + } + nums.push_back(t->val); + int size = nums.size(); + //for(int i = 0; i < size; i++) cout<next==tail) + { + TreeNode* root=new TreeNode(head->val); + return root; + } + ListNode* mid=head; + ListNode* fast=head; + while(fast!=tail&&fast->next!=tail) + { + mid=mid->next; + fast=fast->next->next; + } + TreeNode* root=new TreeNode(mid->val); + root->left=buildBST(head,mid); + root->right=buildBST(mid->next,tail); + return root; + } +}; +``` diff --git a/2018.12.12-leetcode109/Sunny.md b/2018.12.12-leetcode109/Sunny.md new file mode 100644 index 000000000..af231e05b --- /dev/null +++ b/2018.12.12-leetcode109/Sunny.md @@ -0,0 +1,34 @@ +```java +class Solution { + + private List list = new ArrayList<>(); + + public TreeNode sortedListToBST(ListNode head) { + if (head == null) + return null; + addToList(head, 0); + return sortedListToBST(list); + } + + private void addToList(ListNode node, int index) { + if (node != null) { + list.add(node.val); + addToList(node.next, index+1); + } + } + + private TreeNode sortedListToBST(List nums) { + if (nums == null || nums.size() == 0) + return null; + int i = nums.size() / 2; + TreeNode node = new TreeNode(nums.get(i)); + if (i > 0) { + node.left = sortedListToBST(nums.subList(0, i)); + if (i+1 < nums.size()) { + node.right = sortedListToBST(nums.subList(i+1, nums.size())); + } + } + return node; + } +} +``` diff --git a/2018.12.12-leetcode109/TheRocket.md b/2018.12.12-leetcode109/TheRocket.md new file mode 100644 index 000000000..1ac576dae --- /dev/null +++ b/2018.12.12-leetcode109/TheRocket.md @@ -0,0 +1,40 @@ +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + return sortedListToBST(head, null); + } + + private TreeNode sortedListToBST(ListNode head, ListNode end) { + if (head == end) { + return null; + } + ListNode fast = head; + ListNode slow = head; + while (fast != end && fast.next != end) { + fast = fast.next.next; + slow = slow.next; + } + TreeNode root = new TreeNode(slow.val); + root.left = sortedListToBST(head, slow); + root.right = sortedListToBST(slow.next, end); + return root; + } +} +``` diff --git a/2018.12.12-leetcode109/WYJ.md b/2018.12.12-leetcode109/WYJ.md new file mode 100644 index 000000000..9c3dc3a15 --- /dev/null +++ b/2018.12.12-leetcode109/WYJ.md @@ -0,0 +1,27 @@ +class Solution { + private ListNode findNode(ListNode head){ + ListNode prev = head; + ListNode slow = head; + ListNode fast = head; + while(fast != null&&fast.next != null){ + prev = slow; + slow = slow.next; + fast = fast.next.next; + } + prev.next = null; + return slow; + } + public TreeNode sortedListToBST(ListNode head) { + if(head == null){ + return null; + } + ListNode mid = findNode(head); + TreeNode node = new TreeNode(mid.val); + if(mid == head){ + return node; + } + node.left = sortedListToBST(head); + node.right = sortedListToBST(mid.next); + return node; + } +} diff --git a/2018.12.12-leetcode109/marguerite.md b/2018.12.12-leetcode109/marguerite.md new file mode 100644 index 000000000..944cc1117 --- /dev/null +++ b/2018.12.12-leetcode109/marguerite.md @@ -0,0 +1,43 @@ +###leetcode 109. 将双向链表转换成BBST + +####利用快慢指针,找到中间点的前一个点。 + +####然后将root设为中间点的值。 + +####此时将中间左边的链表切出来,进行递归。方法是mid-1的链表结点后继为空。 + +####左边链表从head开始 + +####右边链表从中间结点的下一个开始。 + + +``` +public TreeNode sortedListToBST(ListNode head) { + + //条件判断 + if(head==null) return null; + if(head.next == null) return new TreeNode(head.val); + + //快慢指针 + ListNode fast = head.next.next; + ListNode slow = head; + + while(fast!=null && fast.next!=null){ + fast = fast.next.next; + slow = slow.next; + } + + //找到中点以及右边链表的头部 + ListNode temp = slow.next.next; + TreeNode root = new TreeNode(slow.next.val); + + //切断 + slow.next = null; + + //递归 + root.left = sortedListToBST(head); + root.right = sortedListToBST(temp); + return root; + } + + ``` diff --git a/2018.12.12-leetcode109/sourcema.md b/2018.12.12-leetcode109/sourcema.md new file mode 100644 index 000000000..84e2e5e71 --- /dev/null +++ b/2018.12.12-leetcode109/sourcema.md @@ -0,0 +1,51 @@ +# LeetCode 109 + /** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + class Solution { + public TreeNode sortedListToBST(ListNode head) { + if (head == null) { + return null; + } + if (head.next == null) { + return new TreeNode(head.val); + } + int n=0; + ListNode cur=head; + List list = new ArrayList<>(); + while (cur != null) { + list.add(cur.val); + cur= cur.next; + } + int[] arr =new int[list.size()]; + for (int i = 0; i < arr.length; i++) { + arr[i] = list.get(i); + } + TreeNode root = constructBST(arr, 0, arr.length - 1, new TreeNode(0)); + return root; + } + private TreeNode constructBST(int[] arr, int left, int right, TreeNode head) { + if (left>right||head == null) { + return null; + } + int mid=(left+right)>>1; + head = new TreeNode(arr[mid]); + head.left = constructBST(arr, left, mid - 1, head); + head.right = constructBST(arr, mid + 1, right, head); + return head; + } + } diff --git "a/2018.12.12-leetcode109/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.12-leetcode109/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..1689dc7bd --- /dev/null +++ "b/2018.12.12-leetcode109/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,26 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + if(nums==null||nums.length==0)return null; + return sortToBST(nums,0,nums.length-1); + } + + TreeNode sortToBST(int[] nums,int l,int r){ + if(l>=nums.length||r<0||l>r)return null; + int mid = (l+r)/2; + TreeNode root = new TreeNode(nums[mid]); + root.left=sortToBST(nums,l,mid-1); + root.right=sortToBST(nums,mid+1,r); + return root; + } +} +``` diff --git "a/2018.12.12-leetcode109/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.12.12-leetcode109/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..66a062164 --- /dev/null +++ "b/2018.12.12-leetcode109/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,59 @@ +``` +/** +给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 + +本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 + +示例: + +给定的有序链表: [-10, -3, 0, 5, 9], + +一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: + + 0 + / \ + -3 9 + / / + -10 5 + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + if(head==null){ + return null; + } + return sortedListToBST(head,null); + } + public TreeNode sortedListToBST(ListNode head,ListNode end){ + if(head==end){ + return null; + } + ListNode fast=head; + ListNode slow=head; + while(fast!=end&&fast.next!=end){ + fast=fast.next.next; + slow=slow.next; + } + TreeNode node=new TreeNode(slow.val); + node.left=sortedListToBST(head,slow); + node.right=sortedListToBST(slow.next,end); + + return node; + } + +} +``` diff --git "a/2018.12.12-leetcode109/\345\246\256\345\217\257.md" "b/2018.12.12-leetcode109/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..d572623f4 --- /dev/null +++ "b/2018.12.12-leetcode109/\345\246\256\345\217\257.md" @@ -0,0 +1,109 @@ +```java +package sy181212; + + +/** + * @author suyuan + * +给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 + +本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 + +示例: + +给定的有序链表: [-10, -3, 0, 5, 9], + +一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: + + 0 + / \ + -3 9 + / / + -10 5 + */ +public class leetcode_109有序链表转换二叉搜索树 +{ + + public static void main(String[] args) + { + ListNode node1 = new ListNode(-10); + ListNode node2 = new ListNode(-3); + ListNode node3 = new ListNode(0); + ListNode node4 = new ListNode(5); + ListNode node5 = new ListNode(9); + + node1.next=node2; + node2.next=node3; + node3.next=node4; + node4.next=node5; + + print(sortedListToBST(node1)); + + } + + public static TreeNode sortedListToBST(ListNode head) + { + if(head==null) + return null; + return sortedListToBST(head, null); + } + + public static TreeNode sortedListToBST(ListNode head,ListNode end) + { + //重合,就是left>right + if(head==end) + return null; + ListNode slow=head; + ListNode fast=head; + //快慢指针求链表中点,以快指针为基准 + while(fast!=end&&fast.next!=end) + { + fast=fast.next.next; + slow=slow.next; + } + + TreeNode node=new TreeNode(slow.val); + node.left=sortedListToBST(head, slow);//[left,mid-1] + node.right=sortedListToBST(slow.next, end);//[mid+1,right] + return node; + } + + private static void print(TreeNode tree, int key, int direction) { + + if(tree != null) { + + if(direction==0) // tree是根节点 + System.out.printf("%2d is root\n", tree.val); + else // tree是分支节点 + System.out.printf("%2d is %2d's %6s child\n",tree.val,key, direction==1?"right" : "left"); + + print(tree.left, tree.val, -1); + print(tree.right,tree.val, 1); + } + } + + public static void print(TreeNode node) + { + if (node != null) + print(node, node.val, 0); + } + +} + + class ListNode + { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + + + + class TreeNode + { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } +``` diff --git "a/2018.12.12-leetcode109/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.12-leetcode109/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..a307dedfb --- /dev/null +++ "b/2018.12.12-leetcode109/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,102 @@ +#### [109. Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) - Mark + +**题目描述** +> 给定一个元素都是升序排序的单链表,将其转换成高度平衡的BST。 + +> 高度平衡的二叉树:每个结点两颗子树的深度差不超过1。 + +**例子** +> 给定的有序链表: [-10, -3, 0, 5, 9], 一个可能的答案是:[0, -3, 9, -10, null, 5]。 + +**思想** +(占空间方法) +将列表元素存在数组里,然后对数组进行操作。 + +(法1 - 快慢指针) +想用类似升序数组转成BST的方法。重点是如何把链表分成两半,得到两个子链表。即如何找到链表的中点?此处考虑快慢指针。 + +(法2 - 类似中序遍历) +按照树的中序遍历的方式来构造 + +**解法1** +注意:第一轮循环时把end看出None +```python +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def sortedListToBST(self, head): + """ + :type head: ListNode + :rtype: TreeNode + """ + return self.helper(head, None) + + def helper(self, head, end): + if head == end: + return None + + slow = fast = head + while fast != end and fast.next != end: + slow = slow.next + fast = fast.next.next + + root = TreeNode(slow.val) # Mark + root.left = self.helper(head, slow) + root.right = self.helper(slow.next, end) + + return root +``` +**解法2** +先记录链表长度,然后延用处理数组的方式,对链表结点采取中序遍历(左-根-右)。 +```python +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def sortedListToBST(self, head): + """ + :type head: ListNode + :rtype: TreeNode + """ + size = 0 + self.node = head + while head: + size += 1 + head = head.next + return self.helper(0, size-1) + + def helper(self, l, r): + if l > r: + return None + mid = (l + r) // 2 + # In-order traversal + left = self.helper(l, mid-1) + + root = TreeNode(self.node.val) + root.left = left + self.node = self.node.next + + root.right = self.helper(mid+1, r) + return root +``` \ No newline at end of file diff --git "a/2018.12.12-leetcode109/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.12-leetcode109/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..36c5cd06b --- /dev/null +++ "b/2018.12.12-leetcode109/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,43 @@ +``` +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + if(null==head){ + return null; + } + return getSubBST(head,null); + } + + public TreeNode getSubBST(ListNode head,ListNode tail){ + ListNode slow = head; + ListNode fast = head; + if(tail==head){ + return null; + } + while(fast!=tail&&fast.next!=tail){ + slow = slow.next; + fast = fast.next.next; + } + TreeNode mid = new TreeNode(slow.val); + mid.left = getSubBST(head,slow); + mid.right = getSubBST(slow.next,tail); + return mid; + } +} +``` diff --git "a/2018.12.12-leetcode109/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.12-leetcode109/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..ea213919c --- /dev/null +++ "b/2018.12.12-leetcode109/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,44 @@ +``` +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +/** + * 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 *sortedListToBST(ListNode *head) + { + return sortedListToBST( head, NULL ); + } + +private: + TreeNode *sortedListToBST(ListNode *head, ListNode *tail) + { + if( head == tail ) + return NULL; + + ListNode *mid = head, *temp = head; + while( temp != tail && temp->next != tail ) // 寻找中间节点 + { + mid = mid->next; + temp = temp->next->next; + } + TreeNode *root = new TreeNode( mid->val ); + root->left = sortedListToBST( head, mid ); + root->right = sortedListToBST( mid->next, tail ); + return root; + } +}; +``` diff --git a/2018.12.13-leetcode215/123456.md b/2018.12.13-leetcode215/123456.md new file mode 100644 index 000000000..7e6fc87ac --- /dev/null +++ b/2018.12.13-leetcode215/123456.md @@ -0,0 +1,79 @@ +class Solution { +public: + int n; + vectornums1; + int findKthLargest(vector& nums, int k) { + nums1.push_back(0); + for(int i=0;inums1[2*i]) + { + t=i; + } + else + { + t=2*i; + } + if(i*2+1<=n) + { + if(nums1[t]=1;i--) + { + shiftdown(i); + } + return ; + } + + int DeleteMax() + { + int t; + t=nums1[1]; + nums1[1]=nums1[n]; + n--; + shiftdown(1); + return t; + } +}; diff --git "a/2018.12.13-leetcode215/215. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254K\344\270\252\346\234\200\345\244\247\345\205\203\347\264\240" "b/2018.12.13-leetcode215/215. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254K\344\270\252\346\234\200\345\244\247\345\205\203\347\264\240" new file mode 100644 index 000000000..d4808b641 --- /dev/null +++ "b/2018.12.13-leetcode215/215. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254K\344\270\252\346\234\200\345\244\247\345\205\203\347\264\240" @@ -0,0 +1,13 @@ +在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 + +示例 1: + +输入: [3,2,1,5,6,4] 和 k = 2 +输出: 5 +示例 2: + +输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 +输出: 4 +说明: + +你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 diff --git a/2018.12.13-leetcode215/Avalon.md b/2018.12.13-leetcode215/Avalon.md new file mode 100644 index 000000000..fd61a9404 --- /dev/null +++ b/2018.12.13-leetcode215/Avalon.md @@ -0,0 +1,40 @@ +class Solution { + public int findKthLargest(int[] nums, int k) { + int[] temp = new int[nums.length]; + sort(nums, 0, nums.length - 1, temp); + return nums[nums.length - k]; + } + + private static void sort(int[] arr, int left, int right, int[] temp) { + if (left < right) { + int mid = (left + right) / 2; + sort(arr, left, mid, temp);//左边归并排序,使得左子序列有序 + sort(arr, mid + 1, right, temp);//右边归并排序,使得右子序列有序 + merge(arr, left, mid, right, temp);//将两个有序子数组合并操作 + } + } + + private static void merge(int[] arr, int left, int mid, int right, int[] temp) { + int i = left; + int j = mid + 1; + int t = 0; + while (i <= mid && j <= right) { + if (arr[i] <= arr[j]) { + temp[t++] = arr[i++]; + } else { + temp[t++] = arr[j++]; + } + } + while (i <= mid) {//将左边剩余元素填充进temp中 + temp[t++] = arr[i++]; + } + while (j <= right) {//将右序列剩余元素填充进temp中 + temp[t++] = arr[j++]; + } + t = 0; + //将temp中的元素全部拷贝到原数组中 + while (left <= right) { + arr[left++] = temp[t++]; + } + } +} diff --git a/2018.12.13-leetcode215/Be a fresh man.md b/2018.12.13-leetcode215/Be a fresh man.md new file mode 100644 index 000000000..c0a097278 --- /dev/null +++ b/2018.12.13-leetcode215/Be a fresh man.md @@ -0,0 +1,116 @@ +## 215_(数组中的第K个最大元素)Kth Largest Element in a Array +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
+__说明__:
+你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 +### 1.2 输入与输出 +输入: +* vector& nums:给定未排序的数组的引用 +* int k:第 k 个最大的元素 + +输出: +* int:数组排序后的第 k 个最大的元素 +### 1.3 样例 +#### 1.3.1 样例1 +输入: [3,2,1,5,6,4] 和 k = 2
+输出: 5
+#### 1.3.2 样例2 +输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
+输出: 4
+## 2 思路描述与代码 +### 2.1 思路描述(快排partition+递归方法) +1. 首先介绍下什么叫做快排partition(以从大到小排序为例):
+其目的就是根据第一个值 val 把数组分割成大于第一个值的左半部分与小于第一个值的右边部分,然后再把第一个值与左半部分的最后一个值交换,并返回第一个值交换后的下标,使用的方法就是双边扫描: +```cpp +val = nums[start]; +i = start + 1; +j = end; +while( i <= j ){ + //i <= j 防止越界 + if(i <= j) i 从左向右扫描直至找到 nums[i] < val; + if(i <= j) j 从右向左扫描直至找到 nums[j] > val; + //每一次交换消去了很多逆序对了,所以快速排序很快。 + if(i < j) swap(nums[i], nums[j]); + else break; +} +//交换完毕后,此时的 j 的位置就是大于第一个值的左半部分的最后一个数据 +swap(nums[start], nums[j]); +return j; +``` +比如数组nums[3,2,1,5,6,4],以3为参考点
+i = 1, j = 5, i <= j 成立,第1次交换发生在i = 1, j = 5的时候,此时满足 i < j,交换后为i = 2, j = 4, nums = [3,4,1,5,6,2]
+i = 2, j = 4, i <= j 成立,第2次交换发生在i = 2, j = 4的时候,此时满足 i < j,交换后为i = 3, j = 3, nums = [3,4,6,5,1,2]
+i = 3, j = 3, i <= j 成立, 不满足交换条件,跳出循环;
+此时 j = 3 是大于第一个值的左半部分的最后一个数据,交换 nums[0] 和 nums[3] , nums = [5,4,6, 3, 1,2]
+返回 此时的 j 的下标 3。 + +2. 有了快排partition返回的下标idx(这意味着nums[idx]是第idx + 1大的元素),我们就很容易想到利用其来找数组中的第K个最大元素, +判断准则如下: +* if(pos == k - 1) 则找到了第 k 大的值; +* else if(pos < k - 1) 则第 k - 1个大的值在 nums[idx]的左边,则往左递归快排partition即可; +* else 则第 k - 1个大的值在 nums[idx]的右边,则往右递归快排partition即可; + +3. 这边举个例子比如输入数组nums[3,2,1,5,6,4],k = 2;
+第1次快排partition后, 数组nums = [5,4,6, 3, 1,2],返回下标是3, 意味着 nums[3] = 3 是第 4(3 + 1)大的元素,那么第二大的元素肯定是在左边,于是递归快排partition数组nums的前3个元素[5,4,6];
+第2次快排partition后, 数组nums = [4,5,6, 3,1,2],返回下标1, 意味着 nums[1] = 5 是第 2(1 + 1)大的元素,于是返回5。
+ + +### 2.2 代码 +```cpp +//函数中涉及到的c++知识 +//vector 是个长度可变的int数组,c++里面成为容器 +//ret_func_type func(vector& name) 中的name是vector容器的引用,可以理解为传入一个指针 +//vector::iterator 是c++中的迭代器,可以理解为一个长度可变的int数组的指针类型 + + + +//快排中的一个partition步骤 +//以val = nums[end]为参考点,分离成 比首元素大的节点 + val + 比首元素小的节点 +//返回 val 最后所在的下标 +int partition(vector& nums, int start, int end){ + int i = start + 1; + int j = end; + while( i <= j ){ + while( i <= j && nums[i] > nums[start] ) i++; + while( i <= j && nums[j] < nums[start] ) j--; + if(i < j) swap(nums[i++], nums[j--]); + else break; + } + swap(nums[start], nums[j]); + return j; +} +//基于快排partition的查找第K个最大元素的方法 +int qsort_partition_findKthLargest(vector& nums, int start, int end, int k){ + int pos = partition(nums, start, end); + //如果恰好是第 k - 1 个元素 + if(pos == k - 1) return nums[pos]; + //如果返回的位置比要求的位置大,则说明需要去左边找 + else if(pos > k - 1) return qsort_partition_findKthLargest(nums, start, pos - 1, k); + //如果返回的位置比要求的位置小,则说明需要去右边找 + else return qsort_partition_findKthLargest(nums, pos + 1, end, k); +} + + +int findKthLargest(vector& nums, int k) { + //基于快排partition的查找第K个最大元素的方法 + return qsort_partition_findKthLargest(nums, 0, nums.size() - 1, k); +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题如果了解快排partition的话,则问题很容易可以解决,partition原理也不难。 +#### 3.1.1 其他方法 +#### 3.1.1.1 快排partition+尾递归 +本题可以修改为尾递归的形式,有兴趣的可以尝试一下。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +快排partition+递归|O(logn)|O(nlogn) +快排partition+尾递归|O(1)|O(nlogn) +#### 3.1.3 难点分析 +1. 快排partition的边界考虑 +2. 基于快排partition的递归规则 + +### 3.2 拓展 +如果给你的是链表数据呢? diff --git a/2018.12.13-leetcode215/GatesMa.md b/2018.12.13-leetcode215/GatesMa.md new file mode 100644 index 000000000..97b59b9c2 --- /dev/null +++ b/2018.12.13-leetcode215/GatesMa.md @@ -0,0 +1,13 @@ +# c++ +```cpp +class Solution { +public: + static bool cmp(int a, int b) { + return a > b; + } + int findKthLargest(vector& nums, int k) { + sort(nums.begin(), nums.end(), cmp); + return nums[k-1]; + } +}; +``` diff --git a/2018.12.13-leetcode215/Istoryforever.md b/2018.12.13-leetcode215/Istoryforever.md new file mode 100644 index 000000000..21ebad6b6 --- /dev/null +++ b/2018.12.13-leetcode215/Istoryforever.md @@ -0,0 +1,30 @@ +leetcode of 215 +``` +class Solution { +public: + int partition(vector& nums,int k, int s, int t){ + int i = s - 1; + for(int j = s; j < t; j++){ + if(nums[j] > nums[t]){ + i++; + swap(nums[j],nums[i]); + } + } + i++; + swap(nums[i],nums[t]); + return i; + } + int find(vector& nums,int k, int s,int t){ + int q = partition(nums,k,s,t); + if(q == k - 1) return nums[k-1]; + else if(q < k - 1){ + return find(nums,k,q+1,t); + }else{ + return find(nums,k,s,q-1); + } + } + int findKthLargest(vector& nums, int k) { + return find(nums,k,0,nums.size()-1); + } +}; +``` diff --git a/2018.12.13-leetcode215/MQQM.cpp b/2018.12.13-leetcode215/MQQM.cpp new file mode 100644 index 000000000..e90ced04d --- /dev/null +++ b/2018.12.13-leetcode215/MQQM.cpp @@ -0,0 +1,11 @@ +/* + 题目: + 在未排序的数组中找到第k大的元素。 +*/ +class Solution { +public: + int findKthLargest(vector& nums, int k) { + sort(nums.begin(), nums.end()); + return nums[nums.size()-k]; + } +}; diff --git a/2018.12.13-leetcode215/MQQM2.cpp b/2018.12.13-leetcode215/MQQM2.cpp new file mode 100644 index 000000000..9245298e8 --- /dev/null +++ b/2018.12.13-leetcode215/MQQM2.cpp @@ -0,0 +1,37 @@ +/* + 题目: + 在未排序的数组中找到第k大的元素。 + + 做法:快速排序,分治 + + 参考: + https://blog.csdn.net/a2331046/article/details/53466152?utm_source=blogxgwz2 +*/ +class Solution { +public: + int findKthLargest(vector& nums, int k) { + return findElement(nums, k, 0, nums.size()-1); + } + int findElement(vector& nums, int k, int low, int high) { + int left = low; + int right = high; + int key = nums[left]; + while (left < right) { + while (left < right && nums[right] < key) --right; + nums[left] = nums[right]; + while (left < right && nums[left] >= key) ++left;//注意:这里是>= + nums[right] = nums[left]; + } + nums[left] = key; + //一趟快速排序结束,一个元素归位。该元素下标为left,其左边都比它大,其右边都比它小。 + if (left < (k-1)) {//比如,已经归位的是第4大的元素,欲找第6大的元素。(这里说的第k大从1开始算起,所以减1) + return findElement(nums, k, left+1, high); + } + else if (left > (k-1)) { + return findElement(nums, k, low, left-1); + } + else {//key就是欲找的第k大的元素。 + return key; + } + } +}; diff --git a/2018.12.13-leetcode215/Ostrichcrab.md b/2018.12.13-leetcode215/Ostrichcrab.md new file mode 100644 index 000000000..b58035099 --- /dev/null +++ b/2018.12.13-leetcode215/Ostrichcrab.md @@ -0,0 +1,20 @@ +``` +class Solution { +public: + int findKthLargest(vector& nums, int k) { + sort(nums.begin(),nums.end(),greater()); + return nums[k-1]; + } +}; +``` + +``` +class Solution { +public: + int findKthLargest(vector& nums, int k) { + int size = nums.size(); + nth_element(nums.begin(),nums.begin()+size-k,nums.end()); + return nums[size-k]; + } +}; +``` diff --git a/2018.12.13-leetcode215/Sagittarius.md b/2018.12.13-leetcode215/Sagittarius.md new file mode 100644 index 000000000..0e91c1bb8 --- /dev/null +++ b/2018.12.13-leetcode215/Sagittarius.md @@ -0,0 +1,16 @@ +``` +static auto io_sync_off = [] () { + std::cin.tie(nullptr); + std::ios::sync_with_stdio(false); + std::cout.tie(nullptr); + return nullptr; +}(); +class Solution { +public: + int findKthLargest(vector& nums, int k) { + nth_element(nums.begin(),nums.end()-k,nums.end()); + return nums[nums.size()-k]; + } +}; + +``` diff --git a/2018.12.13-leetcode215/Sunny.md b/2018.12.13-leetcode215/Sunny.md new file mode 100644 index 000000000..a331832c7 --- /dev/null +++ b/2018.12.13-leetcode215/Sunny.md @@ -0,0 +1,16 @@ +```java +class Solution { + public int findKthLargest(int[] nums, int k) { + if (nums == null || nums.length == 0) { + return -1; + } + List sorted = new ArrayList<>(); + for (int i=0; i sorted = Arrays.stream(nums).boxed().collect(Collectors.toList()); + sorted.sort((a,b) -> b-a); + return sorted.get(k-1); + } +} +``` diff --git a/2018.12.13-leetcode215/TheRocket.md b/2018.12.13-leetcode215/TheRocket.md new file mode 100644 index 000000000..60dfe1510 --- /dev/null +++ b/2018.12.13-leetcode215/TheRocket.md @@ -0,0 +1,54 @@ +```java +class Solution { + public int findKthLargest(int[] nums, int k) { + k = nums.length - k; + return quickSelect(nums, k); + } + + private int quickSelect(int[] nums, int k) { + int lo = 0; + int hi = nums.length - 1; + while (lo < hi) { + int i = partition(nums, lo, hi); + if (i < k) { + lo = i + 1; + } else if (i > k) { + hi = i - 1; + } else { + return nums[i]; + } + } + return nums[lo]; + } + + private int partition(int[] nums, int lo, int hi) { + int m = median3(nums, lo, lo + (hi - lo) / 2, hi); + swap(nums, lo, m); + int i = lo; + int j = hi + 1; + int v = nums[lo]; + while (true) { + while (nums[++i] < v && i < hi) {} + while (nums[--j] > v) {} + if (i >= j) { + break; + } + swap(nums, i, j); + } + swap(nums, lo, j); + return j; + } + + private static int median3(int[] nums, int i, int j, int k) { + return nums[i] < nums[j] ? + (nums[j] < nums[k] ? j : nums[i] < nums[k] ? k : i) : + (nums[k] < nums[j] ? j : nums[k] < nums[i] ? k : i); + } + + private void swap(int[] nums, int i, int j) { + int tmp = nums[i]; + nums[i] = nums[j]; + nums[j] = tmp; + } +} +``` diff --git a/2018.12.13-leetcode215/Tony the Cyclist.md b/2018.12.13-leetcode215/Tony the Cyclist.md new file mode 100644 index 000000000..7fb9e96df --- /dev/null +++ b/2018.12.13-leetcode215/Tony the Cyclist.md @@ -0,0 +1,20 @@ +```python +class Solution(object): + def findKthLargest(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + nums.sort(reverse=True) + return nums[k-1] +``` +```java +class Solution { + public int findKthLargest(int[] nums, int k) { + // 经过调优的快速排序法 + Arrays.sort(nums); + return nums[nums.length-k]; + } +} +``` diff --git a/2018.12.13-leetcode215/Typing.txt b/2018.12.13-leetcode215/Typing.txt new file mode 100644 index 000000000..121ea0945 --- /dev/null +++ b/2018.12.13-leetcode215/Typing.txt @@ -0,0 +1,19 @@ +public class Main215 { + public static void main(String[] args){ + Main215 main = new Main215(); + main.test(); + } + + private void test() { + System.out.println(findKthLargest(new int[]{3,2,3,1,2,4,5,5,6},4)); + } + + public int findKthLargest(int[] nums, int k) { + Arrays.sort(nums); + for(int i = nums.length-1;i>=0;i--){ + if (--k==0) + return nums[i]; + } + return nums[0]; + } +} diff --git a/2018.12.13-leetcode215/WYJ.md b/2018.12.13-leetcode215/WYJ.md new file mode 100644 index 000000000..8acf0e8a1 --- /dev/null +++ b/2018.12.13-leetcode215/WYJ.md @@ -0,0 +1,38 @@ +```java +class Solution { + public int findKthLargest(int[] nums, int k) { + return quickSort(nums, 0, nums.length - 1, k); + } + private int quickSort(int[] nums, int L, int R, int k){ + int Lt = R + 1, Gt = L; + int value = nums[L]; + int i = L + 1; + while(i < Lt){ + if(nums[i] < value){ + swap(nums, i, --Lt); + } + else if(nums[i] == value){ + i++; + } + else{ + swap(nums, i++, ++Gt); + } + } + swap(nums, Gt, L); + if(k - 1 >= Gt && k - 1 < Lt){ + return nums[Gt]; + } + else if(k - 1 < Gt){ + return quickSort(nums, L, Gt - 1, k); + } + else{ + return quickSort(nums, Lt, R, k); + } + } + private void swap(int[] nums, int i, int j){ + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} +``` diff --git a/2018.12.13-leetcode215/sourcema.md b/2018.12.13-leetcode215/sourcema.md new file mode 100644 index 000000000..1bcbd87a5 --- /dev/null +++ b/2018.12.13-leetcode215/sourcema.md @@ -0,0 +1,43 @@ +# LeetCode 215 + class Solution { + public int findKthLargest(int[] nums, int k) { + int left=0; + int right=nums.length-1; + int index = partition(nums, left, right); + k=nums.length-k+1;//5个数,第二大就是比他小的数有三个,这个数就是第四小的数 + while (index != k - 1) { + if (index < k - 1) { + left=index+1; + index = partition(nums, left, right); + } else { + right=index-1; + index = partition(nums, left, right); + } + } + return nums[index]; + } + public int partition(int[] arr,int left,int right) { + int pivot=arr[left]; + // int left=start; + // int right=end; + int pivotPointer=left; + while (left < right) { + while (left= pivot) { + right--; + } + // swap(arr, left++, right); + while (leftnums.length)return -1; + // Queue q = new PriorityQueue<>( + // new Comparator(){ + // public int compare(Integer n1,Integer n2){ + // return n2-n1; + // } + // } + // ); + // for(int num:nums){ + // q.offer(num); + // } + // for(int i=0;inums[j]){ + temp=nums[i]; + nums[i]=nums[j]; + nums[j]=temp; + + } + } + } + break; + case 2: + //冒泡排序 + int len=nums.length; + //int temp; + for(int i=0;inums[j+1]){ + temp=nums[j]; + nums[j]=nums[j+1]; + nums[j+1]=temp; + + } + } + } + break; + case 3: + break ; + + + + } + + return nums[nums.length-k]; + } +} +``` diff --git "a/2018.12.13-leetcode215/\345\246\256\345\217\257.md" "b/2018.12.13-leetcode215/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..a115fcc09 --- /dev/null +++ "b/2018.12.13-leetcode215/\345\246\256\345\217\257.md" @@ -0,0 +1,63 @@ +```java +package sy181214; + +import java.util.PriorityQueue; + +/** + * @author suyuan + * + 在未排序的数组中找到第 k 个最大的元素。 + 请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 + +示例 1: + +输入: [3,2,1,5,6,4] 和 k = 2 +输出: 5 +示例 2: + +输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 +输出: 4 +说明: + +你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 + */ +public class leetcode_215数组中的第K个最大元素 +{ + + public static void main(String[] args) + { + int [] input=new int[]{4,5,1,6,2,7,3,2,5,6}; + System.out.println(findKthLargest(input, 4)); + + } + + public static int findKthLargest(int[] nums, int k) + { + int len=nums.length; + if(k>len || k==0) + return 0; + //小顶堆 + PriorityQueue que=new PriorityQueue(k); + for(int i=0;ik) + que.poll(); + } + return que.peek(); + } + +} +``` diff --git "a/2018.12.13-leetcode215/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.13-leetcode215/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..32e7dcb33 --- /dev/null +++ "b/2018.12.13-leetcode215/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,78 @@ +#### [215. Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) +**题目描述** +> 找出数组中第k大的数。 + +> 假设k是有效的,即 1 ≤ k ≤ 数组长度。 + +**例子** +> Example 1: +Input: [3,2,1,5,6,4] and k = 2 +Output: 5 + +> Example 2: +Input: [3,2,3,1,2,4,5,5,6] and k = 4 +Output: 4 + +**思想** +直接排序,然后取出第k大的数 - 时间复杂度O(nlogn) + +(法1 - 快速选择) +快排的思想,每次选定一个基准数,然后将比基准数小的数移到左边,比基准数大的数移到右边... 每次都只考虑一半,直到找到第k个。 +>[时间复杂度] 我们采用随机选取的pivot,所以平均来看每次pivot都选在中间位置。T(n) = O(n + n/2 + n/4 + ... + 2 + 1) = O(2n) = O(n)。 +类似于快排,最好O(n),最差O(n^2),平均O(nlogn). + +(法2 - 堆排序) +首先建k个元素的小顶堆(堆顶元素最小),时间复杂度O(klogk)。然后,剩余的(n-k)个元素依次与堆顶元素x比较,大于x则替换,小于x则忽略;更新堆O(logk)。最后取堆顶元素,即为第k大的数。 +总时间复杂度O(klogk+(n-k)logk) = O(nlogk) + +**解法1** +快速选择。复杂度:时间O(n),空间O(1) +```python +from random import randint +class Solution(object): + def findKthLargest(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + pos = self.quickSort(nums, 0, len(nums)-1) + while pos != len(nums)-k: + if pos > len(nums)-k: + pos = self.quickSort(nums, 0, pos-1) + else: + pos = self.quickSort(nums, pos+1, len(nums)-1) + return nums[pos] + + def quickSort(self, nums, left, right): + pivot = randint(left, right) + # 把基准数放到最后 + number = nums[pivot] + nums[pivot], nums[right] = nums[right], nums[pivot] + # 初始化pos, 指向第一个≥基准数的位置 + pos = left + for i in range(left, right): + if nums[i] < number: + nums[pos], nums[i] = nums[i], nums[pos] + pos += 1 + nums[pos], nums[right] = nums[right], nums[pos] + return pos +``` +**解法2** +堆排序。复杂度:时间O(nlogk),空间O(k) +```python +import heapq +class Solution(object): + def findKthLargest(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + minHeap = [float('-inf')] * k + for num in nums: + if num > minHeap[0]: + heapq.heappop(minHeap) + heapq.heappush(minHeap, num) + return minHeap[0] +``` \ No newline at end of file diff --git "a/2018.12.13-leetcode215/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.13-leetcode215/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..ba6f21d74 --- /dev/null +++ "b/2018.12.13-leetcode215/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,26 @@ +``` +class Solution { +public: + int findKthLargest(vector& nums, int k) { + int left = 0, right = nums.size() - 1; + while (true) { + int pos = partition(nums, left, right); + if (pos == k - 1) return nums[pos]; + else if (pos > k - 1) right = pos - 1; + else left = pos + 1; + } + } + int partition(vector& nums, int left, int right) { + int pivot = nums[left], l = left + 1, r = right; + while (l <= r) { + if (nums[l] < pivot && nums[r] > pivot) { + swap(nums[l++], nums[r--]); + } + if (nums[l] >= pivot) ++l; + if (nums[r] <= pivot) --r; + } + swap(nums[left], nums[r]); + return r; + } +}; +``` diff --git "a/2018.12.13-leetcode215/\351\230\263.md" "b/2018.12.13-leetcode215/\351\230\263.md" new file mode 100644 index 000000000..733da9920 --- /dev/null +++ "b/2018.12.13-leetcode215/\351\230\263.md" @@ -0,0 +1,34 @@ +class Solution { + public int findKthLargest(int[] nums, int k) { + if(nums == null){ + return 0; + }else{ + return findKthLargest(nums, 0, nums.length, k); + } + } + public int findKthLargest(int[] array,int start,int end,int k){ + int temp=array[start]; + int i=start, j=end-1; + while(i!=j){ + while(i=temp) + i++; + if(ik){ + return findKthLargest(array,start,i,k); + }else{ + return findKthLargest(array,i+1,end,k-(i-start+1)); + } + } +} diff --git a/2018.12.14-leetcode347/123456.md b/2018.12.14-leetcode347/123456.md new file mode 100644 index 000000000..7fc3ed1fc --- /dev/null +++ b/2018.12.14-leetcode347/123456.md @@ -0,0 +1,52 @@ +class Solution { +public: + class ShuZi + { + public: + int shuzi; + int Fre; + ShuZi(int shuzi1,int Fre1) + { + shuzi=shuzi1; + Fre=Fre1; + } + friend bool operator<(ShuZi s1,ShuZi s2) + { + return s2.Fre topKFrequent(vector& nums, int k) { + mapmap1; + map::iterator iter; + for(int i=0;ip1; + for(iter=map1.begin();iter!=map1.end();iter++) + { + if(p1.size()first,iter->second); + p1.push(shuzi); + } + else + { + ShuZi shuzi=ShuZi(iter->first,iter->second); + if(shuzi.Fre>p1.top().Fre) + { + p1.pop(); + p1.push(shuzi); + } + } + } + vectorans; + while(!p1.empty()) + { + ans.push_back(p1.top().shuzi); + p1.pop(); + } + return ans; + } +}; diff --git "a/2018.12.14-leetcode347/347. \345\211\215K\344\270\252\351\253\230\351\242\221\345\205\203\347\264\240" "b/2018.12.14-leetcode347/347. \345\211\215K\344\270\252\351\253\230\351\242\221\345\205\203\347\264\240" new file mode 100644 index 000000000..cd964c95c --- /dev/null +++ "b/2018.12.14-leetcode347/347. \345\211\215K\344\270\252\351\253\230\351\242\221\345\205\203\347\264\240" @@ -0,0 +1,14 @@ +给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 + +示例 1: + +输入: nums = [1,1,1,2,2,3], k = 2 +输出: [1,2] +示例 2: + +输入: nums = [1], k = 1 +输出: [1] +说明: + +你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。 +你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。 diff --git a/2018.12.14-leetcode347/Avalon.md b/2018.12.14-leetcode347/Avalon.md new file mode 100644 index 000000000..62226162b --- /dev/null +++ b/2018.12.14-leetcode347/Avalon.md @@ -0,0 +1,30 @@ +class Solution { + public List topKFrequent(int[] nums, int k) { + HashMap map =new HashMap<>(); + int len = nums.length; + Integer tempInt; + Integer current; + for (int i=0;i> list_Data=new ArrayList<>(map.entrySet()); + Collections.sort(list_Data,new Comparator>(){ + + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + return o2.getValue().compareTo(o1.getValue()); + } + }); + List result = new ArrayList<>(); + for (int i=0;i +__说明__: +* 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。 +* 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。 +### 1.2 输入与输出 +输入: +* vector& nums:给定非空整数数组 +* int k:频率前 k 高 + +输出: +* vector:频率前 k 高的元素 +### 1.3 样例 +#### 1.3.1 样例1 +输入: nums = [1,1,1,2,2,3], k = 2
+输出: [1,2] +#### 1.3.2 样例2 +输入: nums = [1], k = 1
+输出: [1] +## 2 思路描述与代码 +### 2.1 思路描述(哈希表+桶排序) +1. 先把数组所有元素插入哈希表 +2. 遍历哈希表, 插入桶中, 桶的下标是哈希表的关键字的个数, 桶的值是哈希表的关键字 +3. 从桶末尾开始遍历桶直到取得桶的高k位数据 + +比如输入[1,1,1,2,2,3] +遍历插入哈希表map后,map = {1:3,2:4,3:1}(顺序是乱的), 其中1:3代表1出现了3次
+然后遍历哈希表,插入桶中,有桶bucket = [[3], [null], [1], [2]]
+从桶末尾开始遍历直至取出两个元素,于是结果是[1, 2]
+### 2.2 代码 +```cpp +//函数中涉及到的c++知识 +//vector 是个长度可变的int数组,c++里面称为容器 +//vector> 是个长度可变且长度不一的二维int数组,每行又是一个长度可变的int数组 +//ret_func_type func(vector& name) 中的name是vector容器的引用,可以理解为传入一个指针 +//unordered_map map是一个无序哈希表,哈希的键值key是唯一的 +//map[val]就是获得val在哈希表map中的个数 + +//时间复杂度O(n) 哈希表+桶排序 +vector topKFrequent(vector& nums, int k) { + //1. 先把数组所有元素插入哈希表 + unordered_map map; + for( int i = 0; i < nums.size(); i++ ) map[nums[i]]++; + //2. 遍历哈希表,插入桶中 + //桶的下标是哈希表关键字的个数, 桶的值是哈希表的关键字 + vector> bucket(nums.size()); + //it->second是关键字的个数,it->first是哈希表的关键字 + for (auto it = map.begin(); it != map.end(); ++it) bucket[it->second - 1].push_back(it->first); + + //3. 从桶末尾开始遍历桶直到取得桶的高k位数据 + vector ans; + int ans_num = 0; + for( int i = nums.size() - 1; i >= 0; i-- ){ + if(bucket[i].size() != 0){ + for( int j = 0; j < bucket[i].size(); j++ ){ + ans.push_back(bucket[i][j]); + if(++ans_num == k) return ans; + } + } + } + //出错 + return {-1}; +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题使用桶排序使得时间复杂度降低为O(n),此外在插入哈希表后你也可以使用优先队列或者最大堆这种的结构来求前k个高频元素。 +#### 3.1.1 其他方法 +#### 3.1.1.1 哈希表+优先队列 +1. 先把数组所有元素插入哈希表 +2. 队列节点的结构是{哈希表的关键字的个数,哈希表的关键字},遍历哈希表, 插入优先队列(以哈希表的关键字的个数从大到小排列)中。 +3. 从优先队列头中取出前k个节点 + +#### 3.1.1.2 哈希表+最大堆 +1. 先把数组所有元素插入哈希表 +2. 堆节点的结构是{哈希表的关键字的个数,哈希表的关键字},遍历哈希表, 插入堆中(以哈希表的关键字的个数从大到小以树形结构排列)中。 +3. 从优先队列头中取出前k个节点 + +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +哈希表+桶排序|O(n)|O(n) +哈希表+优先队列|O(n)|O(nlogn) +哈希表+最大堆|O(n)|O(nlogn) +#### 3.1.3 难点分析 +1. 在插入哈希表后,需要选择以关键字还是关键字的个数来作为排序的依据 + +### 3.2 拓展 +如果给你的是链表数据会影响他的时间与空间复杂度吗? diff --git a/2018.12.14-leetcode347/Istoryforever.md b/2018.12.14-leetcode347/Istoryforever.md new file mode 100644 index 000000000..8816526a9 --- /dev/null +++ b/2018.12.14-leetcode347/Istoryforever.md @@ -0,0 +1,28 @@ +leetcode of 347. Top K Frequent Elements +``` +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map m; + for(auto i : nums){ + if(m.count(i) == 0){ + m[i] = 1; + }else{ + ++m[i]; + } + } + //两种方式,一种是partition,另一种是最小堆 + vector ans; + vector ans_index; + for(auto i = m.begin(); i != m.end(); ++i){ + ans.push_back(i->second); + ans_index.push_back(i->first); + } + sort(ans_index.begin(),ans_index.end(),[&m](int a,int b){ + return m[a] > m[b]; + }); + ans_index.erase(ans_index.begin()+k,ans_index.end()); + return ans_index; + } +}; +``` diff --git a/2018.12.14-leetcode347/MQQM.cpp b/2018.12.14-leetcode347/MQQM.cpp new file mode 100644 index 000000000..6ee1c5df4 --- /dev/null +++ b/2018.12.14-leetcode347/MQQM.cpp @@ -0,0 +1,33 @@ +/* + 题目: + 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 + + 做法: + 遍历一趟,记录每个元素出现的次数,生成一个unordered_map。 + 遍历这个unordered_map,把其元素放入priority_queue(这是一个队列,且队列首元素一直都是最大的)。 + + 参考: + https://blog.csdn.net/a2331046/article/details/52445088 +*/ +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map um; + for(int i=0; i> pq; + for(auto it:um){ + pq.push( make_pair(it.second,it.first) ); + } + + vector rst; + for(int i=0; it.cnt; + } + }p[100004]; + vector topKFrequent(vector& nums, int k) { + vector res; + if(nums.size()==0) return res; + sort(nums.begin(),nums.end()); + p[0].val = nums[0]; p[0].cnt = 0; + int index = 0; + for(int i = 1; i < nums.size(); i++){ + while(p[index].val == nums[i]){ + p[index].cnt++; i++; + } + index++; + p[index].val = nums[i]; + p[index].cnt = 1; + } + sort(p,p+index+1); + for(int i = 0; i < k; i++){ + res.push_back(p[i].val); + } + return res; + } +}; +``` diff --git a/2018.12.14-leetcode347/Sunny.md b/2018.12.14-leetcode347/Sunny.md new file mode 100644 index 000000000..8d8d81120 --- /dev/null +++ b/2018.12.14-leetcode347/Sunny.md @@ -0,0 +1,19 @@ +```java +class Solution { + public List topKFrequent(int[] nums, int k) { + Map map = new HashMap<>(); + for (int n: nums) { + map.put(n, map.getOrDefault(n, 0) + 1); + } + List result = new ArrayList<>(); + PriorityQueue heap = new PriorityQueue<>((a, b) -> map.get(b) - map.get(a)); + for (int num : map.keySet()) { + heap.add(num); + } + for (int j=0; j topKFrequent(int[] nums, int k) { + // 构造一个从整数到出现次数的映射 + Map map = new HashMap<>(); + for (int num : nums) { + map.put(num, map.getOrDefault(num, 0) + 1); + } + // 构造一个桶,桶内存放数据,桶的下标表示该数的出现次数 + List[] buckets = new ArrayList[nums.length + 1]; + for (Map.Entry entry : map.entrySet()) { + int num = entry.getKey(); + int count = entry.getValue(); + if (buckets[count] == null) { + buckets[count] = new ArrayList<>(); + } + buckets[count].add(num); + } + List topK = new ArrayList<>(k); + // 从后往前遍历桶,即从出现次数高的到出现次数低的,注意跳过不存在的桶 + for (int i = buckets.length - 1; i >= 0 && topK.size() < k; --i) { + if (buckets[i] != null) { + topK.addAll(buckets[i]); + } + } + return topK; + } +} +``` diff --git a/2018.12.14-leetcode347/Tony the Cyclist.md b/2018.12.14-leetcode347/Tony the Cyclist.md new file mode 100644 index 000000000..99a4f0adf --- /dev/null +++ b/2018.12.14-leetcode347/Tony the Cyclist.md @@ -0,0 +1,12 @@ +```python +from collections import Counter +class Solution(object): + def topKFrequent(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + c = Counter(nums) + return [item[0] for item in c.most_common(k)] +``` diff --git a/2018.12.14-leetcode347/WYJ.md b/2018.12.14-leetcode347/WYJ.md new file mode 100644 index 000000000..cf2e39901 --- /dev/null +++ b/2018.12.14-leetcode347/WYJ.md @@ -0,0 +1,28 @@ +```java +class Solution { + public List topKFrequent(int[] nums, int k) { + Map map = new HashMap<>(); + List res = new ArrayList<>(); + if(nums.length == 0 || k <= 0){ + return res; + } + for(int i = 0; i < nums.length; i++){ + map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); + } + + for(int i = 0; i < k; i++){ + int tempKey = 99999999; + int tempValue = 0; + for(Integer key : map.keySet()){ + if(map.get(key) > tempValue){ + tempKey = key; + tempValue = map.get(key); + } + } + res.add(tempKey); + map.remove(tempKey); + } + return res; + } +} +``` diff --git a/2018.12.14-leetcode347/sourcema.md b/2018.12.14-leetcode347/sourcema.md new file mode 100644 index 000000000..0f9df3058 --- /dev/null +++ b/2018.12.14-leetcode347/sourcema.md @@ -0,0 +1,25 @@ +# LeetCode 347 + class Solution { + public List topKFrequent(int[] nums, int k) { + Map map = new TreeMap<>(); + for (int i = 0; i < nums.length; i++) { + if (map.containsKey(nums[i])) { + map.put(nums[i], map.get(nums[i]) + 1); + } else { + map.put(nums[i], 1); + } + } + List> list = new ArrayList<>(map.entrySet());//不能直接通过value进行排序,需要转换成List进行排序 + Collections.sort(list, new Comparator>() { + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + return o2.getValue()-o1.getValue(); + } + }); + List res = new ArrayList<>(); + for (int i=0;i topKFrequent(int[] nums, int k) + { + Map map=new HashMap(); + for(int num:nums) + { + map.put(num,map.getOrDefault(num, 0)+1); + } + System.out.println(map); + PriorityQueue queue=new PriorityQueue(k,new Comparator() + { + + @Override + public int compare(Integer o1, Integer o2) + { + //比较的是次数,从大到小,找前TOPK,所以用小顶堆 + return map.get(o1).compareTo(map.get(o2)); + + } + + }); + //比较的数是key + for(int i:map.keySet()) + { + queue.add(i); + //小顶堆的堆顶一定是最小的,poll出去的一定是最小的 + if(queue.size()>k) + queue.poll(); + } + return new ArrayList(queue); + } +} +``` diff --git "a/2018.12.14-leetcode347/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.14-leetcode347/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..0853a0151 --- /dev/null +++ "b/2018.12.14-leetcode347/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,59 @@ +#### [347. Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) +**题目描述** +> 给定非空数组,返回前k个最高频出现的元素。 + +**例子** +> Example 1: +Input: nums = [1,1,1,2,2,3], k = 2 +Output: [1,2] + +>Example 2: +Input: nums = [1], k = 1 +Output: [1] + +**思想** +直观想法,字典存储每个元素出现的次数。然后对字典按值(key = dic.get)降序排序,取出前k个。 +(改进)对dic排序时可参照Topk。 + +**解法** +```python +class Solution(object): + def topKFrequent(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + dic = {} + for num in nums: + if num not in dic: + dic[num] = 1 + else: + dic[num] += 1 + return sorted(dic, key = dic.get, reverse = True)[:k] +``` +改进:以最小堆为例 ~ +```python +import heapq +class Solution(object): + def topKFrequent(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + dic = {} + for num in nums: + if num not in dic: + dic[num] = 1 + else: + dic[num] += 1 + + minHeap = [(float('-inf'), 1)] * k # heapq按x[0]排序 + for key, v in dic.items(): + if v > minHeap[0][0]: + heapq.heappop(minHeap) + heapq.heappush(minHeap, (v, key)) + print(minHeap) + return list(map(lambda x:x[1], minHeap)) +``` \ No newline at end of file diff --git "a/2018.12.14-leetcode347/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.14-leetcode347/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..7db7dd460 --- /dev/null +++ "b/2018.12.14-leetcode347/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,18 @@ +``` +class Solution { +public: + + + vector topKFrequent(vector& nums, int k) { + unordered_map m; + priority_queue> q; + vector res; + for (auto a : nums) ++m[a]; + for (auto it : m) q.push(make_pair(it.second, it.first)); + for (int i = 0; i < k; ++i) { + res.push_back(q.top().second); q.pop(); + } + return res; + } +}; +``` diff --git a/2018.12.15-leetcode451/123456.md b/2018.12.15-leetcode451/123456.md new file mode 100644 index 000000000..5f0d081ff --- /dev/null +++ b/2018.12.15-leetcode451/123456.md @@ -0,0 +1,38 @@ +class Solution { +public: + struct Node + { + char c; + int Frequence; + friend bool operator <(Node N1,Node N2) + { + return N1.Frequencemap1; + for(int i=0;iqueue1; + map::iterator iter; + for(iter=map1.begin();iter!=map1.end();iter++) + { + char c=iter->first; + int F=iter->second; + Node node={c,F}; + queue1.push(node); + } + while(!queue1.empty()) + { + // cout<<"Hello"< topKFrequent(int[] nums, int k) { + HashMap map =new HashMap<>(); + int len = nums.length; + Integer tempInt; + Integer current; + for (int i=0;i> list_Data=new ArrayList<>(map.entrySet()); + Collections.sort(list_Data,new Comparator>(){ + + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + return o2.getValue().compareTo(o1.getValue()); + } + }); + List result = new ArrayList<>(); + for (int i=0;i +输出:"eert"
+解释:'e'出现两次,'r'和't'都只出现一次。因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。 +#### 1.3.2 样例2 +输入:"cccaaa"
+输出:"cccaaa"
+解释:'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。注意"cacaca"是不正确的,因为相同的字母必须放在一起。 +#### 1.3.3 样例3 +输入:"Aabb"
+输出:"bbAa"
+解释:此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。注意'A'和'a'被认为是两种不同的字符。 + +## 2 思路描述与代码 +### 2.1 思路描述(哈希表+桶排序) +1. 先把数组所有元素插入哈希表 +2. 遍历哈希表, 插入桶中, 桶的下标是哈希表的关键字的个数, 桶的值是哈希表的关键字 +3. 从桶末尾开始遍历桶,将每个桶中的元素和个数插入结果字符串中 + +比如输入"tree" +遍历插入哈希表map后,map = {'t':1, 'r':1, 'e':2 }(顺序是乱的), 其中't':1代表't'出现了1次
+然后遍历哈希表,插入桶中(通下标是字符出现的个数-1,桶值是哈希表的字符),有桶bucket = [['r','t'], ['e'], [null], [null]]
+从未尾巴开始遍历桶,得到字符串'eert' +### 2.2 代码 +```cpp +//函数中涉及到的c++知识 +//vector 是个长度可变的int数组,c++里面称为容器 +//vector> 是个长度可变且长度不一的二维int数组,每行又是一个长度可变的int数组 +//ret_func_type func(vector& name) 中的name是vector容器的引用,可以理解为传入一个指针 +//unordered_map map是一个无序哈希表,哈希的键值key是唯一的 +//map[val]就是获得val在哈希表map中的个数 +string frequencySort(string s) { + unordered_map map; + //1. 先插入哈希表 + for( int i = 0; i < s.size(); i++ ) map[s[i]]++; + + vector> bucket(s.size()); + //2. 桶排序 + //it->second是字符出现的个数,it->first是字符 + for (auto it = map.begin(); it != map.end(); ++it) bucket[it->second - 1].push_back(it->first); + //3. 遍历桶 + string ans; + for( int i = bucket.size() - 1; i >= 0; i-- ){ + if(bucket[i].size() != 0){ + for( int j = 0; j < bucket[i].size(); j++ ){ + ans.insert(ans.end(), i+1, bucket[i][j]); + } + } + } + return ans; +} + +``` +## 3 思考与拓展 +### 3.1 思考 +本题使用桶排序使得时间复杂度降低为O(n),此外可以使用快排对哈希表统计的字符频率进行排序。本题与[347_(前K个高频元素)Top K Frequent Element](https://leetcode-cn.com/problems/top-k-frequent-elements/)思路基本一致。 +#### 3.1.1 其他方法 +#### 3.1.1.1 哈希表+快排 +1. 先把数组所有元素插入哈希表 +2. 队列节点的结构是{字符出现的个数,字符},对哈希表统计的字符频率从大到小进行快排(以字符出现的个数从大到小排列)中。 +3. 遍历排序后的数据,获得排列后的字符串 + +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +哈希表+桶排序|O(n)|O(n) +哈希表+快排|O(n)|O(nlogn) + +#### 3.1.3 难点分析 +1. 在插入哈希表后,需要选择以关键字还是关键字的个数来作为排序的依据 + +### 3.2 拓展 +如果给你的是链表数据会影响他的时间与空间复杂度吗? diff --git a/2018.12.15-leetcode451/Istoryforever.md b/2018.12.15-leetcode451/Istoryforever.md new file mode 100644 index 000000000..c5574af6c --- /dev/null +++ b/2018.12.15-leetcode451/Istoryforever.md @@ -0,0 +1,28 @@ +leetcode of 451 +``` +class Solution { +public: + string frequencySort(string s) { + unordered_map m; + for(auto c : s){ + if(m.count(c) == 0){ + m[c] = 1; + }else + ++m[c]; + } + vector ans; + for(auto i = m.begin(); i != m.end(); ++i){ + ans.push_back(i->first); + } + sort(ans.begin(),ans.end(),[&m](char a,char b){ + return m[a] > m[b]; + }); + string res; + for(auto c : ans){ + res+=string(m[c],c); + } + return res; + + } +}; +``` diff --git a/2018.12.15-leetcode451/Ostrichcrab.md b/2018.12.15-leetcode451/Ostrichcrab.md new file mode 100644 index 000000000..c31944299 --- /dev/null +++ b/2018.12.15-leetcode451/Ostrichcrab.md @@ -0,0 +1,17 @@ +``` +class Solution { +public: + string frequencySort(string s) { + int len = s.size(); + unordered_map hash; + vector vec(len+1, ""); + for(auto ch: s) hash[ch]++; + for(auto val: hash) vec[val.second].append(val.second, val.first); + string ans; + for(int i = len; i > 0; i--) + ans += vec[i]; + return ans; + } +}; + +``` diff --git a/2018.12.15-leetcode451/Sagittarius.md b/2018.12.15-leetcode451/Sagittarius.md new file mode 100644 index 000000000..2d4516e2e --- /dev/null +++ b/2018.12.15-leetcode451/Sagittarius.md @@ -0,0 +1,32 @@ +``` +class Solution { +public: + string frequencySort(string s) { + vector res(s.size()+1,""); + map hm; + string st; + + for(auto c:s) + hm[c]++; + + for(auto &it:hm) + { + int n=it.second; + char c=it.first; + res[n].append(n,c); + } + + for(int i=s.size();i>0;i--) + if(!res[i].empty()) + st.append(res[i]); + + return st; + } + +}; +int any = []() { + ios::sync_with_stdio(false); + cin.tie(nullptr); + return 0; +}(); +``` diff --git a/2018.12.15-leetcode451/TheRocket.md b/2018.12.15-leetcode451/TheRocket.md new file mode 100644 index 000000000..ca3c2f84e --- /dev/null +++ b/2018.12.15-leetcode451/TheRocket.md @@ -0,0 +1,30 @@ +```java +class Solution { + public String frequencySort(String s) { + Map map = new HashMap<>(); + for (char c : s.toCharArray()) { + map.put(c, map.getOrDefault(c, 0) + 1); + } + List[] buckets = new ArrayList[s.length() + 1]; + for (Map.Entry entry : map.entrySet()) { + char c = entry.getKey(); + int count = entry.getValue(); + if (buckets[count] == null) { + buckets[count] = new ArrayList<>(); + } + buckets[count].add(c); + } + StringBuilder sb = new StringBuilder(); + for (int i = buckets.length - 1; i >= 0; --i) { + if (buckets[i] != null) { + for (char c : buckets[i]) { + for (int j = 0; j < i; ++j) { + sb.append(c); + } + } + } + } + return sb.toString(); + } +} +``` diff --git a/2018.12.15-leetcode451/Tony the Cyclist.md b/2018.12.15-leetcode451/Tony the Cyclist.md new file mode 100644 index 000000000..99a4f0adf --- /dev/null +++ b/2018.12.15-leetcode451/Tony the Cyclist.md @@ -0,0 +1,12 @@ +```python +from collections import Counter +class Solution(object): + def topKFrequent(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + c = Counter(nums) + return [item[0] for item in c.most_common(k)] +``` diff --git a/2018.12.15-leetcode451/WYJ.md b/2018.12.15-leetcode451/WYJ.md new file mode 100644 index 000000000..76ba38260 --- /dev/null +++ b/2018.12.15-leetcode451/WYJ.md @@ -0,0 +1,31 @@ +```java +class Solution { + public String frequencySort(String s) { + int[] freq = new int[256]; + for(int i = 0; i < s.length(); i++){ + freq[s.charAt(i)]++; + } + char[] res = new char[s.length()]; + for(int i = 0; i < s.length();){ + int index = findMaxIndex(freq); + + for(int j = 0; j < freq[index]; j++){ + res[i++] = (char)index; + } + freq[index] = 0; + } + return String.valueOf(res); + } + public int findMaxIndex(int[] freq){ + int temp = 0; + int index = 0; + for(int i = 0; i < freq.length; i++){ + if(temp < freq[i]){ + temp = freq[i]; + index = i; + } + } + return index; + } +} +``` diff --git a/2018.12.15-leetcode451/sourcema.md b/2018.12.15-leetcode451/sourcema.md new file mode 100644 index 000000000..be171d318 --- /dev/null +++ b/2018.12.15-leetcode451/sourcema.md @@ -0,0 +1,31 @@ +# LeetCode 451 + class Solution { + public String frequencySort(String s) {//先按照value进行排序,然后排在前面的key值根据value的个数添加到最终的String中 + if (s == null || s.length() == 0) { + return s; + } + TreeMap map = new TreeMap<>(); + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + if (map.containsKey(ch)) { + map.put(ch, map.get(ch) + 1); + } else { + map.put(ch, 1); + } + } + List> list = new ArrayList<>(map.entrySet()); + Collections.sort(list, new Comparator>() { + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + return o2.getValue()-o1.getValue(); + } + }); + StringBuilder sb = new StringBuilder(); + for (Map.Entry entry : list) { + for (int i=0;i0) + { + swap(arr, i, lt); + i++; + lt++; + } + else if(compare(arr[i], temp, map)<0) + { + swap(arr, i, gt); + gt--; + } + else { + i++; + } + + } + + sort(arr, low, lt-1,map); + sort(arr, gt+1, high,map); + } + } + + public static int compare(char c1, char c2, int[] map) + { + if (map[c1]==map[c2]){ + return c1 - c2; + } + return map[c1]-map[c2]; + } + + public static void swap(char[]arr,int i,int j) + { + char temp=arr[i]; + arr[i]=arr[j]; + arr[j]=temp; + } + +} +``` diff --git "a/2018.12.15-leetcode451/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.15-leetcode451/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..533b0b389 --- /dev/null +++ "b/2018.12.15-leetcode451/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,54 @@ +#### [451. Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/) + +**题目描述** +> 给定字符串,基于字符出现的次数,对其降序排序。 + +**例子** +> **Example 1:** +Input:"tree" +Output:"eert" + +Explanation: +'e' appears twice while 'r' and 't' both appear once. +So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. + +> **Example 2:** +Input:"cccaaa" +Output:"cccaaa" +Explanation: +Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. +Note that "cacaca" is incorrect, as the same characters must be together. + +> **Example 3:** +Input:"Aabb" +Output:"bbAa" + +Explanation: +"bbaA" is also a valid answer, but "Aabb" is incorrect. +Note that 'A' and 'a' are treated as two different characters. + +**思想** +直观想法,字典存储每个元素出现的次数。然后对字典按值降序排序sorted(dic.items(), key = lambda x:x[1], reverse = True),最后拼接出字符串。 + +**解法** +```python +class Solution(object): + def frequencySort(self, s): + """ + :type s: str + :rtype: str + """ + dic = {} + for c in s: + if c not in dic: + dic[c] = 1 + else: + dic[c] += 1 + + new = sorted(dic.items(), key = lambda x:x[1], reverse = True) + + ss = '' + for c, t in new: + ss += c * t + return ss +``` \ No newline at end of file diff --git "a/2018.12.15-leetcode451/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.15-leetcode451/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..e642aa539 --- /dev/null +++ "b/2018.12.15-leetcode451/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,34 @@ +``` +class Solution { + public String frequencySort(String s) { + //把字符放入哈希表中 + Map map = new HashMap<>(); + for(char c:s.toCharArray()){ + map.put(c,map.getOrDefault(c,0)+1); + } + + //将哈希表放入桶中 + List [] bucket = new List[s.length()+1]; + for(char key:map.keySet()){ + int frequency = map.get(key);//相应字符的频率 + if(bucket[frequency]==null){ + bucket[frequency] = new ArrayList<>(); + } + bucket[frequency].add(key); + } + + StringBuffer sb = new StringBuffer(); + for(int i=bucket.length-1;i>=0;i--){//每个桶 + if(bucket[i]!=null){ + for(char c:bucket[i]){ //每个桶里的几个字符 + for(int j = 0;j m; + for(auto ch:s) m[ch]++; + + priority_queue> p; + for(auto var:m) + p.push(make_pair(var.second, var.first)); + + string ret; + int len = p.size(); + for(int i=0; i list0 = new ArrayList<>();//红色 + List list1 = new ArrayList<>();//白色 + List list2 = new ArrayList<>();//蓝色 + for (int i=nums.length-1;i>=0;i--){ + if (nums[i]==0)list0.add(0); + else if(nums[i]==1)list1.add(1); + else if (nums[i]==2)list2.add(2); + } + + for (int i=0;i +此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
+__注意__: +不能使用代码库中的排序函数来解决这道题。 + +__进阶__: +* 一个直观的解决方案是使用计数排序的两趟扫描算法。首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
+* 你能想出一个仅使用常数空间的一趟扫描算法吗? +### 1.2 输入与输出 +输入: +* vector& nums: 输入的颜色数组 + +输出: +* void:原地修改 +### 1.3 样例 +#### 1.3.1 样例1 +输入: [2,0,2,1,1,0]
+输出: [0,0,1,1,2,2]
+## 2 思路描述与代码 +### 2.1 思路描述(一遍扫描法) +i, j, k分别指向最后的0, 1, 2位置
+一趟扫描元素 x :
+if(x == 0) i, j, k 位置先后置位相应的元素并位置加1
+else if(x == 1) j, k 位置先后置为相应的元素并位置都加1
+else k 位置置为相应的元素并位置都加1
+ +比如输入[2,0,2,1,1,0]
+i, j, k初始化为-1
+x = 2, 下标位置0置2,i = -1, j = -1, k = 0, 此时数组为[2,0,2,1,1,0]
+x = 0, 下标位置1置2,下标位置0置0, i = 0, j = 0, k = 1, 此时数组为[0,2,2,1,1,0]
+x = 2, 下标位置2置2,i = 0, j = 0, k = 2, 此时数组为[0,2,2,1,1,0]
+x = 1, 下标位置3置2,下标位置1置1, i = 0, j = 1, k = 3, 此时数组为[0,1,2,2,1,0]
+x = 1, 下标位置4置2,下标位置2置1, i = 0, j = 2, k = 4, 此时数组为[0,1,1,2,2,0]
+x = 0, 下标位置5置2,下标位置3置1, 下标位置1置0, i = 1, j = 3, k = 5, 此时数组为[0,0,1,1,2,2]
+### 2.2 代码 +```cpp +void sortColors(vector& nums) { + int numsSize = nums.size(); + int i = -1, j = -1, k = -1;//三个指针,i, j, k分别指向最后的0, 1, 2 + //printf("%d %d\n", nums[0], nums[1]); + for(int l=0; l +然后根据个数置0、1、2 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +一遍扫描法|O(1)|0(n) +两遍扫描法|O(1)|0(n),时间复杂度的常数C更大 +#### 3.1.3 难点分析 +1. i, j, k的更新规则 + +### 3.2 拓展 +无。 diff --git a/2018.12.16-leetcode75/Istoryforever.md b/2018.12.16-leetcode75/Istoryforever.md new file mode 100644 index 000000000..3c0482658 --- /dev/null +++ b/2018.12.16-leetcode75/Istoryforever.md @@ -0,0 +1,9 @@ +leetcode of 75 +``` +class Solution { +public: + void sortColors(vector& nums) { + sort(nums.begin(),nums.end()); + } +}; +``` diff --git a/2018.12.16-leetcode75/Ostrichcrab.md b/2018.12.16-leetcode75/Ostrichcrab.md new file mode 100644 index 000000000..ff72f19a3 --- /dev/null +++ b/2018.12.16-leetcode75/Ostrichcrab.md @@ -0,0 +1,25 @@ +``` +class Solution { +public: + void sortColors(vector& nums) { + int red = 0; + int blue = nums.size()-1; + for(int i = 0; i <= blue; i++) + { + if(nums[i] == 0){ + int tmp = nums[i]; + nums[i] = nums[red]; + nums[red] = tmp; + red++; + } + else if(nums[i] == 2){ + int tmp = nums[i]; + nums[i] = nums[blue]; + nums[blue] = tmp; + blue--; + i--; + } + } + } +}; +``` diff --git a/2018.12.16-leetcode75/Sagittarius.md b/2018.12.16-leetcode75/Sagittarius.md new file mode 100644 index 000000000..eb7194d59 --- /dev/null +++ b/2018.12.16-leetcode75/Sagittarius.md @@ -0,0 +1,20 @@ +``` +class Solution { +public: + void sortColors(vector& nums) { + int start=-1; + int end=nums.size(); + int index=0; + while(index1) + swap(nums[--end],nums[index]); + else + index++; + } + + } +}; +``` diff --git a/2018.12.16-leetcode75/TheRocket.md b/2018.12.16-leetcode75/TheRocket.md new file mode 100644 index 000000000..90f7e8c2c --- /dev/null +++ b/2018.12.16-leetcode75/TheRocket.md @@ -0,0 +1,20 @@ +```java +class Solution { + public void sortColors(int[] nums) { + int l = 0; + int r = nums.length; + int i = 0; + while (i < r) { + if (nums[i] < 1) swap(nums, i++, l++); + else if (nums[i] > 1) swap(nums, i, --r); + else ++i; + } + } + + private static void swap(int[] nums, int i, int j) { + int tmp = nums[i]; + nums[i] = nums[j]; + nums[j] = tmp; + } +} +``` diff --git a/2018.12.16-leetcode75/Tony the Cyclist.md b/2018.12.16-leetcode75/Tony the Cyclist.md new file mode 100644 index 000000000..3b89d6592 --- /dev/null +++ b/2018.12.16-leetcode75/Tony the Cyclist.md @@ -0,0 +1,25 @@ +```python +class Solution(object): + def sortColors(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + if len(nums) < 2: + pass + else: + index_0 = 0 + index_2 = len(nums) - 1 + i = 0 + # j = len(nums)-1 + while i < index_2 + 1 and i <= len(nums)-1: + if nums[i] == 0: + nums[index_0], nums[i] = nums[i], nums[index_0] + index_0 += 1 + i += 1 + elif nums[i] == 2: + nums[index_2], nums[i] = nums[i], nums[index_2] + index_2 -= 1 + else: + i += 1 +``` diff --git a/2018.12.16-leetcode75/WYJ.md b/2018.12.16-leetcode75/WYJ.md new file mode 100644 index 000000000..7e14b1ab1 --- /dev/null +++ b/2018.12.16-leetcode75/WYJ.md @@ -0,0 +1,24 @@ +```java +class Solution { + public void sortColors(int[] nums) { + int zero = -1;//nums[0 ... zero] == 0 + int two = nums.length;//nums[two ... length - 1] == 2 + for(int i = 0; i < two;){ + if(nums[i] == 0){ + swap(nums, i++, ++zero); + } + else if(nums[i] == 2){ + swap(nums, i, --two); + } + else{ + i++; + } + } + } + public void swap(int[] nums, int a, int b){ + int temp = nums[b]; + nums[b] = nums[a]; + nums[a] = temp; + } +} +``` diff --git a/2018.12.16-leetcode75/WhiteNight.md b/2018.12.16-leetcode75/WhiteNight.md new file mode 100644 index 000000000..d2d03c1a5 --- /dev/null +++ b/2018.12.16-leetcode75/WhiteNight.md @@ -0,0 +1,33 @@ +```java +/** + * 颜色分类 + */ +public class S4 { + public void sortColors(int[] nums) { //一遍扫描算法 + int Size = nums.length; + int i = -1, j = -1, k = -1; + for (int l = 0; l < Size; l++) { + if (0 == nums[l]){ + nums[++k] = 2; + nums[++j] = 1; + nums[++i] = 0; + } + else if (1 == nums[l]){ + nums[++k] = 2; + nums[++j] = 1; + } + else + nums[++k] = 2; + } + } + + public static void main(String[] args) { + S4 s = new S4(); + int[] nums = {2, 0, 2, 1, 1, 0}; + s.sortColors(nums); + for (int i = 0; i < nums.length; i++) { + System.out.print(nums[i] + " "); + } + } +} +``` \ No newline at end of file diff --git a/2018.12.16-leetcode75/XXXX.md b/2018.12.16-leetcode75/XXXX.md new file mode 100644 index 000000000..637f83d25 --- /dev/null +++ b/2018.12.16-leetcode75/XXXX.md @@ -0,0 +1,3 @@ +## 看了公众号关于GitHub文章过来的,第一次尝试 +## 今天就不写代码了,第一次还不懂规矩,先学会使用GitHub吧 +print("Hello world!") diff --git a/2018.12.16-leetcode75/sourcema.md b/2018.12.16-leetcode75/sourcema.md new file mode 100644 index 000000000..bc92029d7 --- /dev/null +++ b/2018.12.16-leetcode75/sourcema.md @@ -0,0 +1,23 @@ +# LeetCode 75 + class Solution { + public void sortColors(int[] arr) {//借鉴快排partition思路 + if (arr.length == 0 || arr == null) { + return ; + } + int left=-1,right=arr.length,i=0; + while (itemp) { + swap(arr, i, gt); + gt--; + } + else { + i++; + } + } + quicksort(arr, low, lt-1); + quicksort(arr, gt+1, high); + + } + } + + public static void swap(int[]arr,int i,int j) + { + int temp=arr[i]; + arr[i]=arr[j]; + arr[j]=temp; + } + +} +``` diff --git "a/2018.12.16-leetcode75/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.16-leetcode75/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..c817d6570 --- /dev/null +++ "b/2018.12.16-leetcode75/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,70 @@ +#### [75. Sort Colors](https://leetcode.com/problems/sort-colors/) + +**题目描述** +> (三色排序)给出一个由红、白、蓝三种颜色组成的数组,把相同颜色的元素放到一起,并整体按照红、白、蓝的顺序。用0表示红色,1表示白色,2表示蓝色。 + +**例子** +> Input: [2,0,2,1,1,0] +Output: [0,0,1,1,2,2] + +**思想** +(法1) - 遍历两遍 +第一遍可以用三个指针分别对0、1和2进行计数;第二遍赋值 +(法2) - 三指针 +>如果只有两种颜色,那么容易想到一前一后两个指针向中间遍历,颜色不对就交换位置。 +> +三种颜色仍然可以这么做,只不过要多一个指针,前后两个指针用来分隔已经排好的0和2(**保证两指针区间的前面都是0,后面都是2**),中间的指针来遍历元素。 +1)nums[mid]为2,和nums[r]的交换,且更新r -= 1; +2)nums[mid]为1,不需要交换,更新mid += 1; +3)nums[mid]为0,和nums[l]的交换,且更新l += 1。 + +> 假设nums[mid]=0,若mid=l,需要同时右移;若mid > l,则【0,1..l-1】都是0,【l... mid -1】都是1,nums[l]肯定是1。3)中与nums[l]交换后nums[mid]肯定为1,需要更新一下。 + +**解法** +```python +class Solution(object): + def sortColors(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + l = mid = 0 + r = len(nums)-1 + while mid <= r: + if nums[mid] == 0: + nums[l], nums[mid] = nums[mid], nums[l] + l += 1 + mid += 1 + elif nums[mid] == 2: + nums[r], nums[mid] = nums[mid], nums[r] + r -= 1 + else: + mid += 1 +``` +**易懂版** +```python +class Solution(object): + def sortColors(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + l = mid = 0 + r = len(nums)-1 + while mid <= r: + if nums[mid] == 0: + if mid == l: + mid += 1 + l += 1 + else: + nums[l], nums[mid] = nums[mid], nums[l] + l += 1 # nums[mid]值为1, 下一轮需要mid+=1 + elif nums[mid] == 2: + nums[r], nums[mid] = nums[mid], nums[r] + r -= 1 + else: + mid += 1 +``` + +==More== +脑子转不过来,想了很久mid+=1的原因。可以先直接用(拙劣易懂版)做 \ No newline at end of file diff --git "a/2018.12.16-leetcode75/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.16-leetcode75/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..655e253ba --- /dev/null +++ "b/2018.12.16-leetcode75/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,28 @@ +``` +class Solution { +public: + void sortColors(vector& nums) { + int i=0; + int j=nums.size()-1; + + int index = 0; + while(index <= j) + { + if(nums[index]==0 && index!=i) + { + swap(nums[index], nums[i]); + i++; + + } + else if(nums[index]==2) + { + swap(nums[index], nums[j]); + j--; + } + else + index++; + } + + } +}; +``` diff --git a/2018.12.17-leetcode445/Avalon.md b/2018.12.17-leetcode445/Avalon.md new file mode 100644 index 000000000..8ec4dc4a1 --- /dev/null +++ b/2018.12.17-leetcode445/Avalon.md @@ -0,0 +1,34 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + String i1 = String.valueOf(l1.val); + while (l1.next != null) { + i1 = i1.concat(String.valueOf(l1.next.val)); + l1 = l1.next; + } + String i2 = String.valueOf(l2.val); + while (l2.next != null) { + i2 = i2.concat(String.valueOf(l2.next.val)); + l2.next = l2.next.next; + } + + long l = Long.parseLong(i1)+Long.parseLong(i2); + char[] charArr = String.valueOf(l).toCharArray(); + + ListNode current; + ListNode temp = new ListNode(charArr[charArr.length-1] -'0'); + for (int i =charArr.length-2;i>=0;i--){ + current=new ListNode(charArr[i]-'0'); + current.next = temp; + temp = current; + } + return temp; + } +} diff --git a/2018.12.17-leetcode445/Ostrichcrab.md b/2018.12.17-leetcode445/Ostrichcrab.md new file mode 100644 index 000000000..f1c293992 --- /dev/null +++ b/2018.12.17-leetcode445/Ostrichcrab.md @@ -0,0 +1,47 @@ +``` +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + stack stackL1; + stack stackL2; + while(l1){ + stackL1.push(l1->val); + l1=l1->next; + } + while(l2){ + stackL2.push(l2->val); + l2=l2->next; + } + ListNode* head = NULL; + int sum = 0; + while(!stackL1.empty() || !stackL2.empty()){ + sum /= 10; + if(!stackL1.empty()){ + sum+=stackL1.top(); + stackL1.pop(); + } + if(!stackL2.empty()){ + sum+=stackL2.top(); + stackL2.pop(); + } + ListNode* node = new ListNode(sum%10); + node->next = head; + head = node; + } + if(sum>=10){ + ListNode* node = new ListNode(1); + node->next = head; + head = node; + } + return head; + } +}; +``` diff --git a/2018.12.17-leetcode445/oven123.md b/2018.12.17-leetcode445/oven123.md new file mode 100644 index 000000000..c4113a128 --- /dev/null +++ b/2018.12.17-leetcode445/oven123.md @@ -0,0 +1,23 @@ +```java +class Solution { + public int findContentChildren(int[] g, int[] s) { + int sum = 0;int i=0 ;int j=0; + Arrays.sort(g); + Arrays.sort(s); //先对两个数组排序 + for(i = 0,j = 0;i stack1 = new Stack<>(); + Stack stack2 = new Stack<>(); + int ca=0; + ListNode node=null; + while (l1 != null) { + stack1.push(l1.val); + l1=l1.next; + } + while (l2 != null) { + stack2.push(l2.val); + l2=l2.next; + } + while (!stack1.isEmpty() || !stack2.isEmpty()) { + int s1=stack1.isEmpty()?0:stack1.pop(); + int s2=stack2.isEmpty()?0:stack2.pop(); + ListNode cur = new ListNode((s1 + s2 + ca) % 10); + cur.next=node; + node=cur; + ca=(s1+s2+ca)/10; + } + if (ca == 1) { + ListNode cur = new ListNode(1); + cur.next=node; + node=cur; + } + return node; + } +} diff --git "a/2018.12.17-leetcode445/\345\227\257.md" "b/2018.12.17-leetcode445/\345\227\257.md" new file mode 100644 index 000000000..f89a68abb --- /dev/null +++ "b/2018.12.17-leetcode445/\345\227\257.md" @@ -0,0 +1,16 @@ +import java.util.Arrays; +class Solution { + public int findContentChildren(int[] g, int[] s) { + int res = 0; //用来存放的是满足的个数 + Arrays.sort(g);//升序排序 + Arrays.sort(s);//升序排序 + //遍历 + for (int i = 0, j = 0; i < s.length && j < g.length; i++) { + if (s[i] >= g[j]) { + res++; + j++; + } + } + return res; + } +} diff --git "a/2018.12.17-leetcode445/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.17-leetcode445/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..96ac94722 --- /dev/null +++ "b/2018.12.17-leetcode445/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,51 @@ +#### [445. Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/) +**题目描述** +> 给定两个非空链表,代表两个非负整数。高位在链表头部。将两数相加,最终结果也用链表表示。(假设不包含前导0) + +> 不准修正输入的链表(即,不准翻转链表) + +**例子** +> Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) +Output: 7 -> 8 -> 0 -> 7 + +**思想** +先把输入链表转换成数字,然后进行求和。再把求和后的数拆分成链表。 +**注意**:当和为0时,额外处理. + +**解法** +```python +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def addTwoNumbers(self, l1, l2): + """ + :type l1: ListNode + :type l2: ListNode + :rtype: ListNode + """ + num = self.getNum(l1) + self.getNum(l2) + + if not num: + return ListNode(0) + + last = None + while num: + val = num % 10 + num //= 10 + + node = ListNode(val) + node.next = last + last = node + return node + + def getNum(self, l): + res = 0 + while l: + res = res * 10 + l.val + l = l.next + return res +``` \ No newline at end of file diff --git "a/2018.12.17-leetcode445/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.17-leetcode445/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..3921d74d4 --- /dev/null +++ "b/2018.12.17-leetcode445/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,49 @@ +``` +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + ListNode tail1 = reverse(l1); + ListNode tail2 = reverse(l2); + ListNode head = new ListNode(0); + ListNode res = head; + int flag = 0; + while(null!=tail1||null!=tail2){ + int sum = flag; + if(null!=tail1){ + sum += tail1.val; + tail1 = tail1.next; + } + if(null!=tail2){ + sum+=tail2.val; + tail2 = tail2.next; + } + res.next = new ListNode(sum%10); + res = res.next; + flag = sum /10; + } + if(flag==1){ + res.next = new ListNode(flag); + res = res.next; + } + return reverse(head.next); + } + + public ListNode reverse(ListNode head){ + ListNode pre = null; + while(null!=head){ + ListNode next = head.next; + head.next = pre; + pre = head; + head = next; + } + return pre; + } +} +``` diff --git "a/2018.12.17-leetcode445/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.17-leetcode445/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..372cfda07 --- /dev/null +++ "b/2018.12.17-leetcode445/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,75 @@ +``` +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + stack s1; + stack s2; + + ListNode *L1 = l1; + while(L1) + { + s1.push(L1->val); + L1 = L1->next; + } + + L1 = l2; + while(L1) + { + s2.push(L1->val); + L1 = L1->next; + } + + stack s3; + int carry = 0; + while(!s1.empty() && !s2.empty()) + { + int sum = s1.top() + s2.top() + carry; + carry = sum/10; + s3.push(sum%10); + + s1.pop(); + s2.pop(); + } + + while(!s1.empty()) + { + int sum = s1.top() + carry; + carry = sum/10; + s3.push(sum%10); + + s1.pop(); + } + + while(!s2.empty()) + { + int sum = s2.top() + carry; + carry = sum/10; + s3.push(sum%10); + + s2.pop(); + } + + if(carry) s3.push(carry); + + ListNode* ret = new ListNode(-1); + ListNode* p = ret; + while(!s3.empty()) + { + ListNode *node = new ListNode(s3.top()); + p->next = node; + p = p->next; + s3.pop(); + } + + return ret->next; + } +}; +``` diff --git "a/2018.12.17-leetcode455/455. \345\210\206\345\217\221\351\245\274\345\271\262.md" "b/2018.12.17-leetcode455/455. \345\210\206\345\217\221\351\245\274\345\271\262.md" new file mode 100644 index 000000000..eb499b778 --- /dev/null +++ "b/2018.12.17-leetcode455/455. \345\210\206\345\217\221\351\245\274\345\271\262.md" @@ -0,0 +1,31 @@ +假设你是一位很棒的家长,想要给你的孩子们一些小饼干。 +但是,每个孩子最多只能给一块饼干。 +对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。 +如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。 +你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 + +注意: + +你可以假设胃口值为正。 +一个小朋友最多只能拥有一块饼干。 + +示例 1: + +输入: [1,2,3], [1,1] + +输出: 1 + +解释: +你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。 +虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。 +所以你应该输出1。 +示例 2: + +输入: [1,2], [1,2,3] + +输出: 2 + +解释: +你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。 +你拥有的饼干数量和尺寸都足以让所有孩子满足。 +所以你应该输出2. diff --git a/2018.12.17-leetcode455/Avalon.md b/2018.12.17-leetcode455/Avalon.md new file mode 100644 index 000000000..13b1a880e --- /dev/null +++ b/2018.12.17-leetcode455/Avalon.md @@ -0,0 +1,20 @@ +class Solution { + public int findContentChildren(int[] g, int[] s) { + /** + * 第一步:排序 + */ + Arrays.sort(g); + Arrays.sort(s);//按照从小到大进行排序 + int gIndex =0,count = 0; + for (int i=0;i=g[gIndex]){ + count++; + gIndex++; + break; + } + } + } + return count; + } +} diff --git a/2018.12.17-leetcode455/Be a fresh man.md b/2018.12.17-leetcode455/Be a fresh man.md new file mode 100644 index 000000000..58c46067d --- /dev/null +++ b/2018.12.17-leetcode455/Be a fresh man.md @@ -0,0 +1,75 @@ +## 455_(分发饼干)Assign Cookies +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 + +__注意__: +* 你可以假设胃口值为正。 +* 一个小朋友最多只能拥有一块饼干。 +### 1.2 输入与输出 +输入: +* vector< int>& g:孩子胃口尺寸的数组 +* vector< int>& s:饼干尺寸的数组 + +输出: +* int:分发饼干满足孩子的最大数量 +### 1.3 样例 +#### 1.3.1 样例1 +输入: [1,2,3], [1,1]
+输出: 1
+解释: 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。所以你应该输出1。 +#### 1.3.2 样例2 +输入: [1,2], [1,2,3]
+输出: 2
+解释: 你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。你拥有的饼干数量和尺寸都足以让所有孩子满足。所以你应该输出2. +## 2 思路描述与代码 +### 2.1 思路描述(贪心法) +1. 对孩子胃口尺寸的数组 g 和饼干尺寸的数组 s 进行排序; +2. 以先分发较小的饼干为原则分发饼干给孩子(贪心原则) + +比如输入:g = [1,2], s = [1,2,3]
+排序后: g = [1,2], s = [1,2,3]
+先分发s[0]给g[0],再分发s[1]给g[1],可以满足两个孩子,所以输出2 +### 2.2 代码 +```cpp +//函数中涉及到的c++知识 +//vector 是个长度可变的int数组,c++里面称为容器 +//ret_func_type func(vector& name) 中的name是vector容器的引用,可以理解为传入一个指针 +//sort(g.begin(), g.end()) 对容器g的元素从小到大排序,容器的起始数据的指针是 g.begin(),容器的末尾数据的指针是g.end() + +//贪心法 +int findContentChildren(vector& g, vector& s) { + int len_g = g.size(); + int len_s = s.size(); + //先从小到大排序 + sort(g.begin(), g.end()); + sort(s.begin(), s.end()); + //尝试将饼干从小到大分发 + int idx_g = 0, idx_s = 0; + int cnt_satisfy = 0; + while( idx_g < len_g && idx_s < len_s ){ + //能满足这个孩子,继续下个饼干发给下一个孩子 + if(g[idx_g] <= s[idx_s]){ + ++cnt_satisfy; + ++idx_g, ++idx_s; + } + //不能满足这个孩子,换个更大的 + else ++idx_s; + } + return cnt_satisfy; +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题利用贪心原则(先分发较小的饼干为原则分发饼干给孩子)就能解决该问题。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +贪心法|O(1)|O(nlogn),n=max(len_g, len_s) +#### 3.1.3 难点分析 +1. 找到贪心的原则 + +### 3.2 拓展 +如果改变贪心原则为先分发较大的饼干为原则分发饼干给孩子会不会有问题?有什么问题? diff --git a/2018.12.17-leetcode455/TheRocket.md b/2018.12.17-leetcode455/TheRocket.md new file mode 100644 index 000000000..971fb06a2 --- /dev/null +++ b/2018.12.17-leetcode455/TheRocket.md @@ -0,0 +1,17 @@ +```java +class Solution { + public int findContentChildren(int[] g, int[] s) { + Arrays.sort(g); + Arrays.sort(s); + int i = 0; + int j = 0; + while (i < g.length && j < s.length) { + if (s[j] >= g[i]) { + ++i; + } + ++j; + } + return i; + } +} +``` diff --git a/2018.12.17-leetcode455/sourcema.md b/2018.12.17-leetcode455/sourcema.md new file mode 100644 index 000000000..550117ea2 --- /dev/null +++ b/2018.12.17-leetcode455/sourcema.md @@ -0,0 +1,21 @@ +# LeetCode 455 + class Solution { + public int findContentChildren(int[] g, int[] s) {//思路:先把小的饼干分发出去 + if (g == null || g.length == 0 || s == null || s.length == 0) { + return 0; + } + Arrays.sort(g); + Arrays.sort(s); + int count=0; + for (int i = 0, j = 0; i < g.length && j < s.length; ) { + if (s[j] >= g[i]) { + count++; + i++; + j++; + } else { + j++; + } + } + return count; + } +} diff --git "a/2018.12.17-leetcode455/\345\210\230\346\266\246\346\263\275(capture).md" "b/2018.12.17-leetcode455/\345\210\230\346\266\246\346\263\275(capture).md" new file mode 100644 index 000000000..cc0fea8cf --- /dev/null +++ "b/2018.12.17-leetcode455/\345\210\230\346\266\246\346\263\275(capture).md" @@ -0,0 +1,21 @@ +```java + public static int findContentChildren(int[] g, int[] s) { + int count=0; + int index=0; + Arrays.sort(g); + Arrays.sort(s); + for (int i=0;i= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。 + * 你的目标是尽可能满足{越多数量}的孩子,并输出这个最大数值。 + +注意: + +你可以假设胃口值为正。 一个小朋友最多只能拥有一块饼干。 + +示例 1: + +输入: [1,2,3], [1,1] + +输出: 1 + +解释: 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。 +虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。 + 所以你应该输出1。 示例 2: + +输入: [1,2], [1,2,3] + +输出: 2 + +解释: 你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。 +你拥有的饼干数量和尺寸都足以让所有孩子满足。 所以你应该输出2. + + */ +public class leetcode_455分发饼干 +{ + + public static void main(String[] args) + { + int[] g=new int[]{1,2,3}; + int [] s=new int[]{1,3}; + System.out.println(findContentChildren(g, s)); + + } + + //贪心 + //从小到大贪 所以排个序 + public static int findContentChildren(int[] g, int[] s) + { + Arrays.sort(g); + Arrays.sort(s); + int i=0; + int j=0; + int num=0; + //双指针 + while(i 假设你是一位很棒的家长,想给孩子们一些饼干(**每个孩子最多只能给一块饼干**)。 +每个孩子 i 都有一个胃口值 gi (**为正数**),表示满足孩子胃口的饼干最小尺寸;每块饼干 j 的尺寸为 sj 。 +若 sj >= gi ,将该饼干 j 分配给孩子 i ,则孩子会得到满足。 +**目标**:尽可能满足更多的孩子,并输出这个最大数值。 + +**例子** +> **示例 1:** +输入: [1,2,3], [1,1] +输出: 1 + +> **解释:** +你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。 +虽然你有两块饼干,由于尺寸都是1,只能让胃口值是1的孩子满足。所以应该输出1。 + +> **示例 2:** +输入: [1,2], [1,2,3] +输出: 2 + +> **解释:** +你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。 +你拥有的饼干数量和尺寸都足以让所有孩子满足。所以输出2。 + +**思想** +根据胃口值对孩子排序,根据尺寸对饼干排序。双指针,尽可能让小尺寸的饼干满足小胃口的孩子。 + +**解法** +```python +class Solution(object): + def findContentChildren(self, g, s): + """ + :type g: List[int] + :type s: List[int] + :rtype: int + """ + g.sort() + s.sort() + + p1 = p2 = 0 + while p1 < len(g) and p2 < len(s): + if g[p1] <= s[p2]: + p1 += 1 + p2 += 1 + return p1 +``` \ No newline at end of file diff --git "a/2018.12.17-leetcode455/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.17-leetcode455/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..a6346451a --- /dev/null +++ "b/2018.12.17-leetcode455/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,26 @@ +``` +class Solution { +public: + int findContentChildren(vector& g, vector& s) { + sort(g.begin(), g.end()); + sort(s.begin(), s.end()); + + int i = 0; + int j = 0; + int count = 0; + while(i < g.size() && j < s.size()) + { + if(g[i] <= s[j]) + { + i++; + j++; + count++; + } + else + j++; + } + + return count; + } +}; +``` diff --git "a/2018.12.18-leetcode435/435. \346\227\240\351\207\215\345\217\240\345\214\272\351\227\264.md" "b/2018.12.18-leetcode435/435. \346\227\240\351\207\215\345\217\240\345\214\272\351\227\264.md" new file mode 100644 index 000000000..1d18d247e --- /dev/null +++ "b/2018.12.18-leetcode435/435. \346\227\240\351\207\215\345\217\240\345\214\272\351\227\264.md" @@ -0,0 +1,27 @@ +给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。 + +注意: + +可以认为区间的终点总是大于它的起点。 +区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。 +示例 1: + +输入: [ [1,2], [2,3], [3,4], [1,3] ] + +输出: 1 + +解释: 移除 [1,3] 后,剩下的区间没有重叠。 +示例 2: + +输入: [ [1,2], [1,2], [1,2] ] + +输出: 2 + +解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。 +示例 3: + +输入: [ [1,2], [2,3] ] + +输出: 0 + +解释: 你不需要移除任何区间,因为它们已经是无重叠的了。 diff --git a/2018.12.18-leetcode435/Avalon.md b/2018.12.18-leetcode435/Avalon.md new file mode 100644 index 000000000..5ee1493db --- /dev/null +++ b/2018.12.18-leetcode435/Avalon.md @@ -0,0 +1,24 @@ +/** + * Definition for an interval. + * public class Interval { + * int start; + * int end; + * Interval() { start = 0; end = 0; } + * Interval(int s, int e) { start = s; end = e; } + * } + */ +class Solution { + public int eraseOverlapIntervals(Interval[] intervals) { + //按照停止位置进行排序 + Arrays.sort(intervals, (x, y) -> x.end - y.end); + + // + int count = 0, j = 1;//j-下一个 + for (int i = 0; j < intervals.length; j++) { + if (intervals[i].end > intervals[j].start) {//当后一个产生重叠区域时 + count++; + }else i=j;//当不重叠的时候,需要把j的位置作为比较方 + } + return count; + } +} diff --git a/2018.12.18-leetcode435/Be a fresh man.md b/2018.12.18-leetcode435/Be a fresh man.md new file mode 100644 index 000000000..a10005122 --- /dev/null +++ b/2018.12.18-leetcode435/Be a fresh man.md @@ -0,0 +1,95 @@ +## 435_(无重叠区间)Non-overlapping Intervals +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。
+__注意__: +1. 可以认为区间的终点总是大于它的起点。 +2. 区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。 +### 1.2 输入与输出 +输入: +* vector< Interval >& intervals:输入的区间列表 + +输出: +* int:需要移除区间的最小数量 +### 1.3 样例 +#### 1.3.1 样例1 +输入: [ [1,2], [2,3], [3,4], [1,3] ]
+输出: 1
+解释: 移除 [1,3] 后,剩下的区间没有重叠。 +#### 1.3.2 样例2 +输入: [ [1,2], [1,2], [1,2] ]
+输出: 2
+解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。 +#### 1.3.2 样例3 +输入: [ [1,2], [2,3] ]
+输出: 0
+解释: 你不需要移除任何区间,因为它们已经是无重叠的了。 + +## 2 思路描述与代码 +### 2.1 思路描述(贪心法) +贪心原则:对于重叠的两个区间,删去两个区间中右边界较大的那个能使得移除区间的数量最小 + +比如输入[[1,3], [2,5], [4,6]];
+排序后区间列表为[[1,3], [2,5], [4,6]];
+初始化删除重叠区间后的最后一个无重叠区间pre = [-2^31, -2^31];
+初始化删去的区间数目cnt = 0;
+对于区间[1,3],与[-2^31, -2^31]无重叠,pre = [1,3], cnt = 0;
+对于区间[2,5],与[1,3]有重叠,根据贪心原则删去[2,5],pre = [1,3], cnt = 1;
+对于区间[4,6],与[1,3]无重叠,pre = [4,6], cnt = 1;
+返回cnt = 1; +### 2.2 代码 +```cpp +//函数中涉及到的c++知识 +//vector 是个长度可变的Interval数组,c++里面称为容器 +//ret_func_type func(vector& name) 中的name是vector容器的引用,可以理解为传入一个指针 +//sort(g.begin(), g.end(), cmp) 对容器g的Interval元素从小到大排序,容器的起始数据的指针是 g.begin(),容器的末尾数据的指针是g.end() + +//按照区间左边界升序排序 +bool cmp(const Interval& data1, const Interval& data2){ + return (data1.start < data2.start); +} + +class Solution { +public: + int eraseOverlapIntervals(vector& intervals) { + int cnt_erase = 0; + sort(intervals.begin(), intervals.end(), cmp); + //前一个不重复区间的开始与结束 + int start = -1<<31, end = -1<<31; + for( int i = 0; i < intervals.size(); i++ ){ + //如果两个区间没有重叠 + if(intervals[i].start >= end){ + start = intervals[i].start; + end = intervals[i].end; + } + //重叠 + else{ + //如果当前区间在区间内,则移除大的区间 + //不在区间内则删除当前区间,这样子删去的区间最少 + if(intervals[i].end <= end){ + start = intervals[i].start; + end = intervals[i].end; + } + cnt_erase++; + } + } + return cnt_erase; + } +}; +``` +## 3 思考与拓展 +### 3.1 思考 +本题选取好准确的贪心原则后即可简单的解决该问题。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +贪心法|O(1)|O(nlogn) +#### 3.1.3 难点分析 +1. 先要对区间排序,注意区间排序的原则; +2. 选取准确的贪心原则。 + +### 3.2 拓展 +1. [合并区间](https://leetcode-cn.com/problems/merge-intervals/); +2. [插入区间](https://leetcode-cn.com/problems/insert-interval/). diff --git a/2018.12.18-leetcode435/Ostrichcrab.md b/2018.12.18-leetcode435/Ostrichcrab.md new file mode 100644 index 000000000..67b308285 --- /dev/null +++ b/2018.12.18-leetcode435/Ostrichcrab.md @@ -0,0 +1,38 @@ +``` +/** + * Definition for an interval. + * struct Interval { + * int start; + * int end; + * Interval() : start(0), end(0) {} + * Interval(int s, int e) : start(s), end(e) {} + * }; + */ +class Solution { +public: + static bool cmp(Interval a, Interval b){ + if(a.end != b.end) + return a.end& intervals) { + if(intervals.size() == 0) return 0; + int ans = 0; + sort(intervals.begin(),intervals.end(),cmp); + int last = intervals[0].end; + int size = intervals.size(); + for(int i = 1; i < size; i++){ + if(intervals[i].start < last){ + ans++; + }else{ + last = intervals[i].end; + } + } + // for(int i = 0; i < size; i++){ + // cout< o.end)); + int res = 0; + int pre = intervals[0].end; + for (int i = 1; i < intervals.length; ++i) { + if (intervals[i].start < pre) { + ++res; + } else { + pre = intervals[i].end; + } + } + return res; + } +} +``` diff --git a/2018.12.18-leetcode435/WYJ.md b/2018.12.18-leetcode435/WYJ.md new file mode 100644 index 000000000..4823c3c59 --- /dev/null +++ b/2018.12.18-leetcode435/WYJ.md @@ -0,0 +1,33 @@ +```java +/** + * Definition for an interval. + * public class Interval { + * int start; + * int end; + * Interval() { start = 0; end = 0; } + * Interval(int s, int e) { start = s; end = e; } + * } + */ +class Solution { + public int eraseOverlapIntervals(Interval[] intervals) { + if(intervals.length == 0){ + return 0; + } + Comparator cmp = new Comparator(){ + public int compare(Interval a, Interval b){ + return a.end - b.end; + } + }; + Arrays.sort(intervals,cmp); + int end = intervals[0].end; + int count = 1; + for(int i = 1; i < intervals.length; i++){ + if(intervals[i].start >= end){ + count++; + end = intervals[i].end; + } + } + return intervals.length - count; + } +} +``` diff --git a/2018.12.18-leetcode435/marguerite.md b/2018.12.18-leetcode435/marguerite.md new file mode 100644 index 000000000..321f174dd --- /dev/null +++ b/2018.12.18-leetcode435/marguerite.md @@ -0,0 +1,42 @@ + 1 /** + 2 ###Definition for an interval. + + 3 ###public class Interval { + + 4 ### int start; + + 5 ### int end; + + 6 ### Interval() { start = 0; end = 0; } + + 7 ### Interval(int s, int e) { start = s; end = e; } + + 8 ### } + 9 */ + ``` +10 public class Solution { +11 public int eraseOverlapIntervals(Interval[] intervals) { +12 if(intervals.length == 0) return 0; +13 +14 Comparator comp = new Comparator() { +15 public int compare(Interval interval1, Interval interval2) { +16 if(interval1.end > interval2.end) return 1; +17 else if(interval1.end < interval2.end) return -1; +18 else return 0; +19 } +20 }; +21 +22 Arrays.sort(intervals, comp); +23 int lastend = intervals[0].end; +24 int remove = 0; +25 for(int i = 1; i < intervals.length; i++) { +26 if(intervals[i].end == lastend) remove++; +27 else if(intervals[i].start < lastend) remove++; +28 else lastend = intervals[i].end; +29 } +30 +31 return remove; +32 } +33 } + +``` diff --git a/2018.12.18-leetcode435/sourcema.md b/2018.12.18-leetcode435/sourcema.md new file mode 100644 index 000000000..a19364211 --- /dev/null +++ b/2018.12.18-leetcode435/sourcema.md @@ -0,0 +1,25 @@ +# leetcode 435 + class Solution { + public int eraseOverlapIntervals(Interval[] intervals) { + if (intervals == null || intervals.length == 0||intervals.length==1) { + return 0; + } + + Arrays.sort(intervals, new Comparator() {//不按照start比较,按照end比较 + @Override + public int compare(Interval o1, Interval o2) { + return o1.end-o2.end; + } + }); + int count=0; + int index=1; + for (int i = 0; index < intervals.length; index++) { + if (intervals[i].end > intervals[index].start) { + count++; + } else { + i=index; + } + } + return count; + } +} diff --git "a/2018.12.18-leetcode435/\345\246\256\345\217\257.md" "b/2018.12.18-leetcode435/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..283156d8a --- /dev/null +++ "b/2018.12.18-leetcode435/\345\246\256\345\217\257.md" @@ -0,0 +1,93 @@ +```java +package sy181223; + +import java.util.Arrays; +import java.util.Comparator; + +/** + * @author suyuan + * + 给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。 + +注意: + +可以认为区间的终点总是大于它的起点。 区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。 + 示例 1: + +输入: [ [1,2], [2,3], [3,4], [1,3] ] + +输出: 1 + +解释: 移除 [1,3] 后,剩下的区间没有重叠。 示例 2: + +输入: [ [1,2], [1,2], [1,2] ] + +输出: 2 + +解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。 示例 3: + +输入: [ [1,2], [2,3] ] + +输出: 0 + +解释: 你不需要移除任何区间,因为它们已经是无重叠的了。 + + */ +public class leetcode_435无重叠区间 +{ + + public static void main(String[] args) + { + Interval i1=new Interval(1,2); + Interval i2=new Interval(1,3); + Interval i4=new Interval(5,6); + Interval i3=new Interval(3,4); + + Interval[] intervals=new Interval[]{i1,i2,i3,i4}; + System.out.println(eraseOverlapIntervals(intervals)); + + } + + public static int eraseOverlapIntervals(Interval[] intervals) + { + if(intervals==null || intervals.length==0) + return 0; + //按末尾排序 + Arrays.sort(intervals,new Comparator() + { + + @Override + public int compare(Interval o1, Interval o2) + { + return o1.end-o2.end; + } + + }); + + int len=intervals.length; + int count=1; + int i=0; + for(int j=1;j 给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。 + +> 可以认为区间的终点总是大于它的起点。 +区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。 + +**例子** +> **示例 1:** +输入: [ [1,2], [2,3], [3,4], [1,3] ] +输出: 1 +**解释**: 移除 [1,3] 后,剩下的区间没有重叠。 + +> **示例2:** +输入: [ [1,2], [1,2], [1,2] ] +输出: 2 + **解释**: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。 + +> **示例 3:** +输入: [ [1,2], [2,3] ] +输出: 0 + **解释**: 你不需要移除任何区间,因为它们已经是无重叠的了。 + +**思想** +先将区间按左侧排序。如果interval1.end > interval2.start,则说明interval1和interval2重叠。 +1)若interval1.end > interval2.end,则interval1包含interval2,重叠区域为interval2 → 移除interval1 +2)若interval1.end < interval2.end,则重叠区域为[interval2.start, interval1.end]→ 移除interval2 + +双指针,指针 i 用来遍历所有区间,指针 j 指示上一个保留的区间。 + +**解法** +```python +# Definition for an interval. +# class Interval(object): +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + +class Solution(object): + def eraseOverlapIntervals(self, intervals): + """ + :type intervals: List[Interval] + :rtype: int + """ + cnt = 0 + j = 0 + intervals.sort(key = lambda x:x.start) + for i in range(1, len(intervals)): + # overlap + if intervals[j].end > intervals[i].start: + cnt += 1 + if intervals[j].end > intervals[i].end: + j = i + else: + j = i + return cnt +``` +改进:end标记指示上一个保留的区间的end +```python +# Definition for an interval. +# class Interval(object): +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + +class Solution(object): + def eraseOverlapIntervals(self, intervals): + """ + :type intervals: List[Interval] + :rtype: int + """ + if not intervals: + return 0 + + intervals.sort(key = lambda x:x.start) + end = intervals[0].end + + cnt = 0 + for interval in intervals[1:]: + # overlap + if end > interval.start: + cnt += 1 + end = min(end, interval.end) + else: + end = interval.end + return cnt +``` \ No newline at end of file diff --git "a/2018.12.18-leetcode435/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.18-leetcode435/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..657d760c9 --- /dev/null +++ "b/2018.12.18-leetcode435/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,28 @@ +``` +class Solution { +public: + int eraseOverlapIntervals(vector& intervals) { + if(intervals.size() <= 1) return 0; + + int ret = 0; + sort(intervals.begin(), intervals.end(), [](Interval& a, Interval& b){return a.start < b.start;}); + + auto tmp = intervals.begin(); + auto it=intervals.begin(); + it++; + for(; it!=intervals.end(); it++) + { + if(tmp->end > it->start) + { + ret++; + tmp = (tmp->end>it->end)?it:tmp; + } + else + tmp = it; + } + + return ret; + + } +}; +``` diff --git "a/2018.12.19-leetcode452/452. \347\224\250\346\234\200\345\260\221\346\225\260\351\207\217\347\232\204\347\256\255\345\274\225\347\210\206\346\260\224\347\220\203.md" "b/2018.12.19-leetcode452/452. \347\224\250\346\234\200\345\260\221\346\225\260\351\207\217\347\232\204\347\256\255\345\274\225\347\210\206\346\260\224\347\220\203.md" new file mode 100644 index 000000000..5f706898a --- /dev/null +++ "b/2018.12.19-leetcode452/452. \347\224\250\346\234\200\345\260\221\346\225\260\351\207\217\347\232\204\347\256\255\345\274\225\347\210\206\346\260\224\347\220\203.md" @@ -0,0 +1,21 @@ +在二维空间中有许多球形的气球。 +对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。 +由于它是水平的,所以y坐标并不重要,因此只要知道开始和结束的x坐标就足够了。 +开始坐标总是小于结束坐标。平面内最多存在104个气球。 + +一支弓箭可以沿着x轴从不同点完全垂直地射出。 +在坐标x处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足 xstart ≤ x ≤ xend,则该气球会被引爆。 +可以射出的弓箭的数量没有限制。 +弓箭一旦被射出之后,可以无限地前进。 +我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。 + +Example: + +输入: +[[10,16], [2,8], [1,6], [7,12]] + +输出: +2 + +解释: +对于该样例,我们可以在x = 6(射爆[2,8],[1,6]两个气球)和 x = 11(射爆另外两个气球)。 diff --git a/2018.12.19-leetcode452/Avalon.md b/2018.12.19-leetcode452/Avalon.md new file mode 100644 index 000000000..f0233eb8d --- /dev/null +++ b/2018.12.19-leetcode452/Avalon.md @@ -0,0 +1,21 @@ +class Solution { + public int findMinArrowShots(int[][] points) { + if (points == null || points.length == 0) return 0; + //对二位数组进行排序 + Arrays.sort(points, (x, y) -> x[1] - y[1]); + + //开始落实比较方案 + //1-无重叠区域 + int count = 0, j = 1; + for (int i = 0; j < points.length; j++) { + if (points[i][1] >= points[j][0]) {//被比较方的结束大于比较方的开始--重叠了-》 + + } else { + count++;//因为这个是后结算的,所以需要在最后return 的时候自加 + i = j; + } + } + + return ++count;//当最后一个出现的时候是木有进行判断 + } +} diff --git a/2018.12.19-leetcode452/Be a fresh man.md b/2018.12.19-leetcode452/Be a fresh man.md new file mode 100644 index 000000000..962a27189 --- /dev/null +++ b/2018.12.19-leetcode452/Be a fresh man.md @@ -0,0 +1,84 @@ +## 452_(用最少数量的箭引爆气球)Minimum Number of Arrows to Burst Balloons +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以y坐标并不重要,因此只要知道开始和结束的x坐标就足够了。开始坐标总是小于结束坐标。平面内最多存在104个气球。
+ +一支弓箭可以沿着x轴从不同点完全垂直地射出。在坐标x处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足 xstart ≤ x ≤ xend,则该气球会被引爆。可以射出的弓箭的数量没有限制。
弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。 +### 1.2 输入与输出 +输入: +* vector>& points:气球直径坐标的列表 + +输出: +* int:最少数量的箭 +### 1.3 样例 +#### 1.3.1 样例1 +输入:[[10,16], [2,8], [1,6], [7,12]]
+输出:2
+解释:对于该样例,我们可以在x = 6(射爆[2,8],[1,6]两个气球)和 x = 11(射爆另外两个气球)。 + +## 2 思路描述与代码 +### 2.1 思路描述(贪心法) +1. 先按右边界从大到小排序 +2. 确定贪心准则:在区间的右边界引爆气球可以使用最少数量的箭引爆气球 + 然后遍历区间 + * 若当前区间的左边界大于上一次引爆的地方,说明进入了爆破后的非重复区域,此时继续在其右边界引爆 + * 否则说明其依旧处于当前爆破点的爆破范围 + + +比如输入:points = [[10,16], [2,8], [1,6], [7,12]];
+last_end 记录上一次引爆的右边界,cnt 记录爆破的次数;
+1. 以右边界排序后有:points = [[1,6], [2,8], [7,12], [10,16]];
+2. 遍历区间: + * 区间[1,6], 在其右边界引爆气球, last_end = 6,cnt = 1;
+ * 区间[2:8], 2 < last_end, 仍处于可爆破的地方, last_end = 8,cnt = 1;
+ * 区间[7,12], 7 > last_end, 在其右边界引爆气球, last_end = 12,cnt = 2;
+ * 区间[10,16], 10 < last_end, 仍处于可爆破的地方, last_end = 12,cnt = 2;
+于是返回2。 +### 2.2 代码 +```cpp +//函数中涉及到的c++知识 +//pair tmp可以理解为含有两个int变量的结构体数组,其第1个元素为tmp.first, 第2个元素为tmp.second +//vector> 是个长度可变的结构体(含有两个int变量)数组,c++里面称为容器 +//ret_func_type func(vector>& name) 中的name是vector>容器的引用,可以理解为传入一个指针 +//sort(g.begin(), g.end()) 对容器g的元素从小到大排序,容器的起始数据的指针是 g.begin(),容器的末尾数据的指针是g.end() + +//贪心法 +//1. 先按右边界从大到小排序 +//2. 确定贪心准则:在区间的右边界引爆气球 +// 然后遍历区间 +// * 若当前区间的左边界大于上一次引爆的地方,说明进入了爆破后的非重复区域,此时继续在其右边界引爆 +// * 否则说明其依旧处于当前爆破点的爆破范围 +int findMinArrowShots(vector>& points) { + if(points.size() == 0) return 0; + int cnt_arrow = 1; + sort(points.begin(), points.end(), cmp); + int last_end = points[0].second; + for( int i = 1; i < points.size(); i++ ){ + if(points[i].first > last_end){ + cnt_arrow++; + last_end = points[i].second; + } + } + return cnt_arrow; +} + +static bool cmp(const pair& point1, const pair& point2){ + return point1.second < point2.second; +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题的关键在于以右边从小到大排序,然后贪心准则(在区间的右边界引爆气球可以使用最少数量的箭引爆气球)才是对的。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +贪心法|O(1)|O(nlogn) + +#### 3.1.3 难点分析 +1. 确定以右边界对气球区间从小到大排序; +2. 确定贪心准则:在区间的右边界引爆气球可以使用最少数量的箭引爆气球。 + +### 3.2 拓展 +本题如果以左边界对气球区间从小到大排序、以同样的贪心准则会出现什么问题? diff --git a/2018.12.19-leetcode452/Ostrichcrab.md b/2018.12.19-leetcode452/Ostrichcrab.md new file mode 100644 index 000000000..6d7757ebe --- /dev/null +++ b/2018.12.19-leetcode452/Ostrichcrab.md @@ -0,0 +1,23 @@ +``` +class Solution { +public: + static bool cmp(pair a, pair b){ + if(a.first!=b.first) return a.second>& points) { + int size = points.size(); + if(size == 0)return 0; + int ans = 1; + sort(points.begin(),points.end(),cmp); + int last = points[0].second; + for(int i = 1; i < size; i++){ + if(points[i].first > last){ + ans++; + last = points[i].second; + } + } + return ans; + } +}; +``` diff --git a/2018.12.19-leetcode452/TheRocket.md b/2018.12.19-leetcode452/TheRocket.md new file mode 100644 index 000000000..49ca369e7 --- /dev/null +++ b/2018.12.19-leetcode452/TheRocket.md @@ -0,0 +1,19 @@ +```java +class Solution { + public int findMinArrowShots(int[][] points) { + if (points == null || points.length == 0) { + return 0; + } + Arrays.sort(points, Comparator.comparingInt(o -> o[1])); + int res = 1; + int pre = points[0][1]; + for (int i = 1; i < points.length; ++i) { + if (points[i][0] > pre) { + ++res; + pre = points[i][1]; + } + } + return res; + } +} +``` diff --git a/2018.12.19-leetcode452/WYJ.md b/2018.12.19-leetcode452/WYJ.md new file mode 100644 index 000000000..1acebdf59 --- /dev/null +++ b/2018.12.19-leetcode452/WYJ.md @@ -0,0 +1,25 @@ +```java +class Solution { + public int findMinArrowShots(int[][] points) { + if(points.length == 0){ + return 0; + } + Comparator cmp = new Comparator(){ + public int compare(int[] points1, int[] points2){ + return points1[1] - points2[1]; + } + }; + Arrays.sort(points, cmp); + int end = points[0][1]; + int count = 1; + for(int i = 1; i < points.length; i++){ + if(points[i][0] > end){ + count++; + end = points[i][1]; + } + } + return count; + + } +} +``` diff --git a/2018.12.19-leetcode452/marguerite.md b/2018.12.19-leetcode452/marguerite.md new file mode 100644 index 000000000..21043cb5b --- /dev/null +++ b/2018.12.19-leetcode452/marguerite.md @@ -0,0 +1,37 @@ + + 这道题目是活动选择问题(Activity-Selection Problem)的变形。活动选择问题是《算法导论》里面关于贪心算法的第一个问题。这个问题是这样的。有一组活动, + 每个活动都有一个开始时间S和结束时间F,假设一个人在同一时间只能参加一个活动,找出出一个人可以参加的最多的活动数量。例如。 + +假设现在有6个活动,下面是6个活动的起始和结束时间。 + start[] = {1, 3, 0, 5, 8, 5}; + finish[] = {2, 4, 6, 7, 9, 9}; + 一个人一天最多能参见的活动为 + {0, 1, 3, 4} + +关于活动选择问题就不在详细解说了。这道题非常算是变形。将所有的气球按照终止位置排序,开始从前向后扫描。以第一个气球的终止位置为准, +只要出现的气球起始位置小于这个气球的终止位置,代表可以一箭使这些气球全部爆炸;当出现一个气球的起始位置大于第一 +个气球的终止位置时再以这个气球的终止位置为准,找出所有可以再一箭爆炸的所有气球;以此类推。。。 + + + ``` + public int findMinArrowShots(int[][] points) { + if (points == null || points.length == 0 || points[0].length == 0) { + return 0; + } + Arrays.sort(points, new Comparator() { + public int compare(int[] a, int[] b) { + return a[1] - b[1]; + } + }); + + long lastEnd = Long.MIN_VALUE; + int minArrows = 0; + for (int i = 0; i < points.length; i++) { + if (lastEnd < points[i][0]) { + lastEnd = points[i][1]; + minArrows++; + } + } + return minArrows; + } +``` diff --git a/2018.12.19-leetcode452/sourcema.md b/2018.12.19-leetcode452/sourcema.md new file mode 100644 index 000000000..7175c1c34 --- /dev/null +++ b/2018.12.19-leetcode452/sourcema.md @@ -0,0 +1,28 @@ +# LeetCode 452 + class Solution { + public int findMinArrowShots(int[][] points) {//按照每个坐标的end排序,然后看与当前坐标重叠的坐标最远到哪,超出当前坐标范围更新count,更新坐标位置 + if (points == null || points.length == 0 || points[0].length == 0) { + return 0; + } + if (points.length == 1) { + return 1; + } + Arrays.sort(points, new Comparator() { + @Override + public int compare(int[] o1, int[] o2) { + return o1[1] - o2[1]; + } + }); + int count = 1; + int index = 1; + for (int i = 0; index < points.length; index++) { + if (points[i][1] >= points[index][0]) { + continue; + } else { + count++; + i = index; + } + } + return count; + } +} diff --git "a/2018.12.19-leetcode452/\345\246\256\345\217\257.md" "b/2018.12.19-leetcode452/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..01eff63e0 --- /dev/null +++ "b/2018.12.19-leetcode452/\345\246\256\345\217\257.md" @@ -0,0 +1,81 @@ +```java +package sy181223; + +import java.util.Arrays; +import java.util.Comparator; + +/** + * @author suyuan + * + 在二维空间中有许多球形的气球。 + 对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。 + 由于它是水平的,所以y坐标并不重要,因此只要知道开始和结束的x坐标就足够了。 + 开始坐标总是小于结束坐标。平面内最多存在104个气球。 + +一支弓箭可以沿着x轴从不同点完全垂直地射出。 +在坐标x处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, +且满足 xstart ≤ x ≤ xend,则该气球会被引爆。 +可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。 +我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。 + +Example: + +输入: [[10,16], [2,8], [1,6], [7,12]] + +输出: 2 + +解释: +对于该样例,我们可以在x = 6(射爆[2,8],[1,6]两个气球)和 x = 11(射爆另外两个气球)。 + +http://www.cnblogs.com/MrSaver/p/9499139.html + */ +public class leetcode_452用最少数量的箭引爆气球 +{ + + public static void main(String[] args) + { + int[][] a={{10,16},{2,8},{1,6},{7,12}}; + System.out.println(findMinArrowShots(a)); + + + } + + public static int findMinArrowShots(int[][] points) + { + if(points==null ||points.length==0) + return 0; + Arrays.sort(points, new Comparator() + { + + @Override + public int compare(int[] o1, int[] o2) + { + return o1[1]-o2[1]; + } + + }); + + int count=1; + //左边的值不管,右边的最小值 + //当左边的下一个值大于右边的最小值 + //一支箭 + //换人 + + //右边的最小值 + int temp=points[0][1]; + for(int i=1;itemp) + { + count++; + //更新右边的最小值 + temp=points[i][1]; + } + } + return count; + + } + +} +``` diff --git "a/2018.12.19-leetcode452/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.19-leetcode452/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..be98ba70f --- /dev/null +++ "b/2018.12.19-leetcode452/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,59 @@ +#### [452. Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) +**题目描述** +> 在二维空间有许多球形气球。对每个气球,输入是**水平方向**上气球直径的**开始和结束坐标**(开始坐标总是小于结束坐标)。 + +> 记一个气球直径的开始和结束坐标为 xstart,xend。在坐标x处射出一支箭,若 xstart ≤ x ≤ xend,则该气球会被引爆。 +可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。 +求所需弓箭的最小数量,使所有气球都被引爆。 + +**例子** +> Input: [[10,16], [2,8], [1,6], [7,12]] +Output: 2 +**Explanation:** +One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons). + +**思想** +和重叠区间有关~ +首先区间按start排序;依次遍历区间,若两区间重叠,记录重叠区域;然后判断下一个区间是否和该重叠区域重合。若重合,继续记录重叠区域;否则弓箭数+1。 +(改进) +按end排序 + +**解法** +```python +class Solution(object): + def findMinArrowShots(self, points): + """ + :type points: List[List[int]] + :rtype: int + """ + if not points: + return 0 + + cnt = 1 + points = sorted(points, key = lambda x:x[0]) + end = points[0][1] + for point in points[1:]: + if end >= point[0]: # overlap + end = min(end, point[1]) + else: + end = point[1] + cnt += 1 + return cnt +``` +改进:按end排序 +```python +class Solution(object): + def findMinArrowShots(self, points): + """ + :type points: List[List[int]] + :rtype: int + """ + points = sorted(points, key = lambda x:x[1]) + cnt = 0 + end = float('-inf') + for point in points: + if point[0] > end: # non-overlap + cnt += 1 + end = point[1] + return cnt +``` \ No newline at end of file diff --git "a/2018.12.19-leetcode452/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.19-leetcode452/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..8f3d9b9fc --- /dev/null +++ "b/2018.12.19-leetcode452/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,28 @@ +``` +class Solution { + public int findMinArrowShots(int[][] points) { + if(null==points||points.length==0||points[0].length==0){ + return 0; + } + //比较器,将points数组排序 + Arrays.sort(points,new Comparator(){ + public int compare(int[] a,int[] b){ + return a[0]==b[0]?a[1]-b[1]:a[0]-b[0]; + } + }); + + int minArrow = 1; + int arrowLimit = points[0][1];//第一个气球的右边界 + for(int i=0;i &a, const std::pair &b) +{ + return a.first>& points) { + if(points.size() <= 1) return points.size(); + + int ret = 1; + sort(points.begin(), points.end(), cmp); + + auto tmp = points.begin(); + auto it = points.begin(); + it++; + for(; itsecond >= it->first) + { + tmp->first = it->first; + tmp->second = min(tmp->second, it->second); + } + else + { + tmp = it; + ret++; + } + } + + return ret; + } +}; + +``` diff --git a/2018.12.2-leetcode557/-.md b/2018.12.2-leetcode557/-.md new file mode 100644 index 000000000..917fbba93 --- /dev/null +++ b/2018.12.2-leetcode557/-.md @@ -0,0 +1,29 @@ +public class Solution_557 { + public String reverseWords(String s) { + StringBuilder tmp = new StringBuilder(); + StringBuilder result = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) != ' ') { + tmp.append(s.charAt(i)); + } else { + if (result.length() != 0) { + result.append(" "); + } + //System.out.println(tmp.toString()); + result.append(tmp.reverse().toString()); + tmp.setLength(0); + } + } + if (tmp.length() != 0) { + if (result.length() != 0) { + result.append(" "); + } + result.append(tmp.reverse().toString()); + } + return result.toString(); + } + + public static void main(String[] args) { + System.out.println(new Solution_557().reverseWords("Let's take LeetCode contest")); + } +} diff --git a/2018.12.2-leetcode557/123456 122 b/2018.12.2-leetcode557/123456 122 new file mode 100644 index 000000000..76070d4ea --- /dev/null +++ b/2018.12.2-leetcode557/123456 122 @@ -0,0 +1,83 @@ +#include +#include +#include +using namespace std; +class Solution { +public: + vector> solveNQueens(int n) { + vector>a; + vectorpos(n,-1); + SolvenQueensProblem(n,0,pos,a); + return a; + } + void SolvenQueensProblem(int n,int row,vector&pos,vector>&a) + { + // cout<s(n,string(n,'.')); + + for(int i=0;i>a=solution.solveNQueens(4); + for(int i=0;i<1;i++) + { + for(int j=0;j<2;j++) + { + // cout< +#include +using namespace std; +class Solution { +public: + string reverseWords(string s) { + string s1=""; + int i=0,j=s.find(' '); + if(j==-1) + { + for(int i=s.size()-1;i>=0;i--) + { + // cout<=i;h--) + { + s1=s1+s[h]; + } + i=j+1; + s1=s1+' '; + position=j; + // cout<position;p-- ) + { + s1=s1+s[p]; + } + + return s1; + } +}; +int main() +{ + string s2="hehhhhhhe"; + Solution s; + string s3= s.reverseWords(s2); + cout<=0;i--){ + sb.append(chars[i]); + } + sb.append(" "); + } + return sb.toString().trim(); + } + + +} diff --git a/2018.12.2-leetcode557/Avalon.md b/2018.12.2-leetcode557/Avalon.md new file mode 100644 index 000000000..a0544f122 --- /dev/null +++ b/2018.12.2-leetcode557/Avalon.md @@ -0,0 +1,17 @@ +class Solution { + public String reverseWords(String s) { + String[] sArr = s.split(" "); + StringBuilder sb = new StringBuilder(); + int len = sArr.length; + for (int i=0;i +__注意__:
+在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 +### 1.2 输入与输出 +输入: +* string s:输入的字符串s + +输出: +* string:反转字符串后的字符串 +### 1.3 样例 +#### 1.3.1 样例1 +输入: "Let's take LeetCode contest"
+输出: "s'teL ekat edoCteeL tsetnoc" +## 2 思路描述与代码 +### 2.1 思路描述(单词反转法) +start 记录字符串中每个单词的起始位置 +```cpp +for( c in String s which is s[i]){ + if(c == ' '){ + reverse s.substr(start, i); + start = i + 1; + } +} +``` +### 2.2 代码 +```cpp +string reverseWords(string s) { + s += ' '; + int len = s.size(); + int start = 0; + for( int i = 0; i < len; i++ ){ + if(s[i] == ' '){ + reverse(s.begin() + start, s.begin() + i); + start = i + 1; + } + } + s.pop_back(); + return s; +} +``` +## 3 思考与拓展 +### 3.1 思考 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +单词反转法|O(1)|O(n) +#### 3.1.3 难点分析 +1. 如何记录起始位置 +2. 如何处理字符串的最后一个单词 +### 3.2 拓展 +如果给你的是链表数据或者数组数据呢? diff --git a/2018.12.2-leetcode557/GatesMa.md b/2018.12.2-leetcode557/GatesMa.md new file mode 100644 index 000000000..8a115488a --- /dev/null +++ b/2018.12.2-leetcode557/GatesMa.md @@ -0,0 +1,24 @@ +# c++ +```cpp +class Solution { +public: + string reverseWords(string s) { + stringstream ss; + string temstr, str; + ss << s; + vector strs; + while(ss){ + ss >> temstr; + reverse(temstr.begin(),temstr.end()); + strs.push_back(temstr); + } + strs.pop_back(); + int len = strs.size(); + str += strs[0]; + for(int i =1;i < len;i++){ + str += " " + strs[i]; + } + return str; + } +}; +``` diff --git a/2018.12.2-leetcode557/HCL6666HCL.md b/2018.12.2-leetcode557/HCL6666HCL.md new file mode 100644 index 000000000..18326e73c --- /dev/null +++ b/2018.12.2-leetcode557/HCL6666HCL.md @@ -0,0 +1,7 @@ +String.prototype.reverse = function() { + return this.split('').reverse().join(''); +} + +var reverseWords = function(s) { + return s.split(' ').map(str => str.reverse()).join(' '); +}; diff --git a/2018.12.2-leetcode557/Istoryforever.md b/2018.12.2-leetcode557/Istoryforever.md new file mode 100644 index 000000000..a1ce499c8 --- /dev/null +++ b/2018.12.2-leetcode557/Istoryforever.md @@ -0,0 +1,21 @@ +leetcode of 557 +class Solution { +public: + string reverseWords(string s) { + string ans; + string t; + stringstream ss(s); + int start = 1; + while(getline(ss,t,' ')){ + reverse(t.begin(),t.end()); + if(start){ + ans = t; + start = 0; + }else{ + ans += " "+t; + } + } + return ans; + + } +}; diff --git a/2018.12.2-leetcode557/Ostrichcrab.md b/2018.12.2-leetcode557/Ostrichcrab.md new file mode 100644 index 000000000..1912b6d0a --- /dev/null +++ b/2018.12.2-leetcode557/Ostrichcrab.md @@ -0,0 +1,19 @@ +``` +class Solution { +public: + string reverseWords(string s) { + s+=" "; + int len = s.length(); + int left = 0, right = 0; + for(int i = 0; i < len; i++){ + while(s[i]!=' ') right++,i++; + reverse(s.begin()+left,s.begin()+right); + right++; + left=right; + } + s.pop_back(); + cout< a; + int i=0; + while(i>word){ + reverse(word.begin(), word.end()); + result += word + " "; + } + if(!result.empty()) + { + result.erase(result.find_last_not_of(" ")+1); + } + return result; + } +}; +``` diff --git a/2018.12.2-leetcode557/kiritocly.md b/2018.12.2-leetcode557/kiritocly.md new file mode 100644 index 000000000..a7d5c40d7 --- /dev/null +++ b/2018.12.2-leetcode557/kiritocly.md @@ -0,0 +1,22 @@ + private static String solution(String input) { + String[] splits = input.split(" "); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < splits.length; i++) { + //对每个字符串进行反转 + sb.append(reverse(splits[i]) + " "); + } + return sb.toString(); + } + + private static String reverse(String str) { + char[] charArray = str.toCharArray(); + int i = 0, j = charArray.length - 1; + while (i < j) { + char temp = charArray[i]; + charArray[i] = charArray[j]; + charArray[j] = temp; + i++; + j--; + } + return String.valueOf(charArray); + } diff --git a/2018.12.2-leetcode557/sourcema.md b/2018.12.2-leetcode557/sourcema.md new file mode 100644 index 000000000..efa6b231c --- /dev/null +++ b/2018.12.2-leetcode557/sourcema.md @@ -0,0 +1,29 @@ +# leetcode 557 + class Solution { + public String reverseWords(String s) { + if (s == null || s.length() == 0) { + return s; + } + int start=s.charAt(0)!=' '?0:1; + int end=-1; + char[] chars = s.toCharArray(); + for (int i = 0; i < chars.length; i++) { + if (chars[i] == ' ') { + end=i-1; + change(chars, start, end); + start=i+1; + } + } + change(chars, start, chars.length - 1); + return String.valueOf(chars); + } + private void change(char[] chars, int start, int end) { + while (start < end) { + char temp = chars[start]; + chars[start] = chars[end]; + chars[end]=temp; + start++; + end--; + } + } +} diff --git a/2018.12.2-leetcode557/syuan.md b/2018.12.2-leetcode557/syuan.md new file mode 100644 index 000000000..b8de3acd6 --- /dev/null +++ b/2018.12.2-leetcode557/syuan.md @@ -0,0 +1,33 @@ +##### 题目 +给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 + +示例 1: + +输入: "Let's take LeetCode contest" +输出: "s'teL ekat edoCteeL tsetnoc" + +注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 +##### 代码 + +``` +public class Solution { + public String reverseWords(String s) { + + if(s == null){ return null;} + + String[] strChar=s.split(" "); + int size=strChar.length; + //reverse every vocabulary + String reverse=""; + for (int i=0; i> tmp;//第一个字符串单独处理 + res += reverse(tmp); + // cout << reverse(tmp); + while (is >> tmp) { + // cout << " " << reverse(tmp); + res += " "; + res += reverse(tmp); + } + return res; + } + string reverse(string& s) { + string res = s; + int n = s.size() - 1; + for (int i = 0; i < s.size(); ++i) { + res[i] = s[n-i]; + } + return res; + } +}; +``` diff --git "a/2018.12.2-leetcode557/\343\200\202V1ncentzzZ.md" "b/2018.12.2-leetcode557/\343\200\202V1ncentzzZ.md" new file mode 100644 index 000000000..45a71bdb7 --- /dev/null +++ "b/2018.12.2-leetcode557/\343\200\202V1ncentzzZ.md" @@ -0,0 +1,55 @@ +557. 反转字符串中的单词 III + +给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 + +示例 1: + +输入: "Let's take LeetCode contest" +输出: "s'teL ekat edoCteeL tsetnoc" +注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 + +class Solution { + + // https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/submissions/ + + // TODO 空复O(1) 未AC + // public String reverseWords(String s) { + // s = s.trim(); + // if(s.length() < 2) return s; + // char[] wordChar = s.toCharArray(); + // String result = ""; + // for(int i=0; i<=wordChar.length; i++){ + // if(i == wordChar.length || ' ' == wordChar[i]){ + // for(int j=i-1; j>=0; j--){ + // if(wordChar[j] == ' ' && j != wordChar.length - 1) { + // result += " "; + // break; + // } + // if(j == 0) result += " "; + // // if(result.equals("") && wordChar[j] == ' ') continue; + // // if(j == wordChar.length-1) + // result += wordChar[j]; + // } + // continue; + // } + // } + // return result; + // } + + + public String reverseWords(String s) { + String[] strs = s.split(" "); + StringBuilder sb = new StringBuilder(); + for(String str:strs){ + char[] chars = str.toCharArray(); + for(int i=0,j=chars.length-1;i= 1; j-=2){ + char temp = chars[len]; + chars[len] = chars[len+j]; + chars[len+j] = temp; + len++; + } + len = i+1; + } + } + return new String(chars); + } diff --git "a/2018.12.2-leetcode557/\344\272\221\346\267\261\344\270\215\345\217\271.md" "b/2018.12.2-leetcode557/\344\272\221\346\267\261\344\270\215\345\217\271.md" new file mode 100644 index 000000000..cb20d8f84 --- /dev/null +++ "b/2018.12.2-leetcode557/\344\272\221\346\267\261\344\270\215\345\217\271.md" @@ -0,0 +1,15 @@ +``` + public String reverseWords(String s) { + String[] arr = s.split(" "); + StringBuilder sb = new StringBuilder(); + for (String str : arr){ + char[] chars = str.toCharArray(); + for (int i = chars.length -1; i>=0;i--){ + sb.append(chars[i]); + } + sb.append(" "); + } + return sb.substring(0,sb.length()-1); + + } +``` diff --git "a/2018.12.2-leetcode557/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.2-leetcode557/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..20fb52343 --- /dev/null +++ "b/2018.12.2-leetcode557/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,27 @@ +```java +class Solution { + public String reverseWords(String s) { + if(s.length()<=0)return s; + int l=0; + int r=0; + char[] str=s.toCharArray(); + int n=s.length(); + while(true){ + while(r=0;j--){//遍历每段字符串中的每个字符,从后往前添加。 + if(cArray[j]!=' '){ + sb.append(cArray[j]);//如果为不为空字符,添加 + } + } + sb.append(" ");//添加字符串也就是题意的单词之后,添加空字符。 + } + + + return sb.toString().trim(); + } +} +``` diff --git "a/2018.12.2-leetcode557/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" "b/2018.12.2-leetcode557/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" new file mode 100644 index 000000000..eff6896d9 --- /dev/null +++ "b/2018.12.2-leetcode557/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" @@ -0,0 +1,22 @@ +#leetcode557 + ``` + class Solution { + public String reverseWords(String s) { + String[] words=s.split(" "); + StringBuffer result=new StringBuffer(); + for(String temp :words){ + int i=0; + char[] chars=temp.toCharArray(); + for(char c:chars){ + i++; + } + for(i--;i>=0;i--){ + result.append(chars[i]); + } + result.append(" "); + } + result.deleteCharAt(result.length() - 1); + return result.toString(); + } +} + ``` diff --git "a/2018.12.2-leetcode557/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.2-leetcode557/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..f12e33f9c --- /dev/null +++ "b/2018.12.2-leetcode557/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,24 @@ +#### [557. Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) +**题目描述** +> 给定字符串,翻转字符串中每个单词的字符,保留空白和初始的单词顺序。 + +> 字符串中,单词间用空格分隔,且没有额外的空格。 + +**例子** +> Input: "Let's take LeetCode contest" +Output: "s'teL ekat edoCteeL tsetnoc" + +**思想** +首先split出每个单词。 +**解法** +```python +class Solution(object): + def reverseWords(self, s): + """ + :type s: str + :rtype: str + """ + return ' '.join(map(lambda x:x[::-1], s.split())) + # return ' '.join(s.split()[::-1])[::-1] + # return ' '.join(s[::-1].split()[::-1]) +``` \ No newline at end of file diff --git "a/2018.12.2-leetcode557/\346\235\250jia.md" "b/2018.12.2-leetcode557/\346\235\250jia.md" new file mode 100644 index 000000000..c61d8ca63 --- /dev/null +++ "b/2018.12.2-leetcode557/\346\235\250jia.md" @@ -0,0 +1,25 @@ +class Solution { + public String reverseWords(String s) { + String [] list = s.split(" "); + StringBuffer result = new StringBuffer(); + for(int i=0;i-1;i--) { + charry[j++]=ch[i]; + } + str = String.valueOf(charry); + return str; + } +} diff --git "a/2018.12.2-leetcode557/\351\235\222\350\241\253\345\277\206\347\254\231.md" "b/2018.12.2-leetcode557/\351\235\222\350\241\253\345\277\206\347\254\231.md" new file mode 100644 index 000000000..790d0aff0 --- /dev/null +++ "b/2018.12.2-leetcode557/\351\235\222\350\241\253\345\277\206\347\254\231.md" @@ -0,0 +1,26 @@ +class Solution { + public String reverseWords(String s) { + if(s==null||s.length()==0) { + return new String(); + } + String[] str=s.split(" "); + StringBuffer sb=new StringBuffer(); + for(int i=0;ix[0]==y[0]?x[1]-y[1]:y[0]-x[0]); + + List templist = new LinkedList<>(); + for (int[] p : + people) { + templist.add(p[1], p); + } + return templist.toArray(new int[templist.size()][]); + } +} diff --git a/2018.12.20-leetcode406/Be a fresh man.md b/2018.12.20-leetcode406/Be a fresh man.md new file mode 100644 index 000000000..5e6bc83eb --- /dev/null +++ b/2018.12.20-leetcode406/Be a fresh man.md @@ -0,0 +1,90 @@ +## 406_(根据身高重建队列)Queue Reconstruction by Height +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。 + +__注意__: +总人数少于1100人。 +### 1.2 输入与输出 +输入: +* vector>& people: 长度可变的结构体数组的引用 people + +输出: +* vector>: 重建之后的长度可变结构体数组 +### 1.3 样例 +#### 1.3.1 样例1 +输入:[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
+输出:[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] + +## 2 思路描述与代码 +### 2.1 思路描述(排序重建法) +1. 按身高 h 从大到小排列,身高相等按 k 从小到大排序 +2. 按照规则(当前(h, k)插入的位置为第 k 个元素)重建队列 + + +比如输入:people = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] +1. 排序后people = [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]] +2. 按照规则(当前(h, k)插入的位置为第 k 个元素)重建队列 +* [7,0]插入第 0 个位置,有 ans = [[7,0]]; +* [7,1]插入第 1 个位置,有 ans = [[7,0], [7,1]]; +* [6,1]插入第 1 个位置,有 ans = [[7,0], [6,1], [7,1]]; +* [5,0]插入第 0 个位置,有 ans = [[5,0], [7,0], [6,1], [7,1]]; +* [5,2]插入第 2 个位置,有 ans = [[5,0], [7,0], [5,2], [6,1], [7,1]]; +* [4,4]插入第 4 个位置,有 ans = [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]; + +### 2.2 代码 +```cpp +//函数中涉及到的c++知识 +//pair 可以理解为包含两个元素的结构体 +//vector> 是个长度可变的结构体数组,c++里面称为容器 +//ret_func_type func(vector>& name) 中的name是vector>容器的引用,可以理解为传入一个指针 +//sort(g.begin(), g.end(), cmp) 对容器g的结构体按照cmp的排序规则排序,容器的起始数据的指针是 g.begin(),容器的末尾数据的指针是g.end() + +//1. 按身高 h 从大到小排列,身高相等按 k 从小到大排序 +//2. 重建队列 +vector> reconstructQueue(vector>& people) { + int len = people.size(); + vector> ans; + //1. 按身高 h 从大到小排列,身高相等按 k 从小到大排序 + sort(people.begin(), people.end(), cmp); + //2. 重建队列 + for( int i = 0; i < len; i++ ){ + ans.insert(ans.begin() + people[i].second, people[i]); + } + return ans; +} +//按身高 h 从大到小排列,身高相等按 k 从小到大排序 +static bool cmp(const pair& data1, const pair& data2){ + return data1.first != data2.first ? data1.first > data2.first : data1.second < data2.second; +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题按照排序规则排序后,很容易找到重排后应插入的位置。 +#### 3.1.1 其他方法 +#### 3.1.1.1 排序+BIT(二分索引树) +1. 按照以 h 从小到达, h 相同以 k 从小到达排序 +2. 遍历排序后的结构体数组,借助BIT(二分索引树)可以在O(logn)时间内找到未用的第 k 个位置。 + +比如输入:people = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] +1. 排序后people = [[4,4], [5,0], [5,2], [6,1], [7,0], [7,1]] +2. 按照规则(当前(h, k)插入的位置为第 k 个可用元素)重建队列 +* pos = [1,1,1,1,1,1], [4,4]插入第 4 + 1 个可用位置,有pos = [1,1,1,1,0,1], ans = [[-1,-1],[-1,-1],[-1,-1],[-1,-1],[4,4],[-1,-1]]; +* pos = [1,1,1,1,0,1], [5,0]插入第 0 + 1 个可用位置,有pos = [0,1,1,1,0,1], ans = [[5,0],[-1,-1],[-1,-1],[-1,-1],[4,4],[-1,-1]]; +* pos = [0,1,1,1,0,1], [5,2]插入第 2 - 1 + 1 个可用位置(相同元素需要减掉),有pos = [0,1,0,1,0,1], ans = [[5,0],[-1,-1],[5,2],[-1,-1],[4,4],[-1,-1]]; +* pos = [0,1,0,1,0,1], [6,1]插入第 1 + 1 个可用位置,有pos = [0,0,1,0,0,1], ans = [[5,0],[-1,-1],[5,2],[6,1],[4,4],[-1,-1]]; +* pos = [0,0,1,0,0,1], [7,0]插入第 0 + 1 个可用位置,有pos = [0,0,0,0,0,1], ans = [[5,0],[7,0],[5,2],[6,1],[4,4],[-1,-1]]; +* pos = [0,0,0,0,0,1], [7,1]插入第 0 + 1 个可用位置,有pos = [0,0,0,0,0,0], ans = [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] + + +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +排序重建法|O(1)|平均O(nlogn),最差O(n^2) +排序+BIT(二分索引树)|O(n)|O(nlogn) +#### 3.1.3 难点分析 +1. 找到合理的排序规则; +2. 根据合理的规则对排序后的结构体数组重建 + +### 3.2 拓展 +如果让你实现BIT(二分索引树)呢? diff --git a/2018.12.20-leetcode406/Ostrichcrab.md b/2018.12.20-leetcode406/Ostrichcrab.md new file mode 100644 index 000000000..ba2d95bd0 --- /dev/null +++ b/2018.12.20-leetcode406/Ostrichcrab.md @@ -0,0 +1,15 @@ +``` +class Solution { +public: + vector> reconstructQueue(vector>& people) { + vector> result; + sort(people.begin(), people.end(), [](pair a, pair b){ + return a.first > b.first || (a.first == b.first && a.second < b.second); + }); + for(auto p : people){ + result.insert(result.begin()+p.second, p); + } + return result; + } +}; +``` diff --git a/2018.12.20-leetcode406/Sagittarius.md b/2018.12.20-leetcode406/Sagittarius.md new file mode 100644 index 000000000..f8e563635 --- /dev/null +++ b/2018.12.20-leetcode406/Sagittarius.md @@ -0,0 +1,16 @@ +``` +class Solution { +public: + vector> reconstructQueue(vector>& people) { + auto cmp=[](const pair& p1,const pair& p2) + {return p1.first>p2.first||(p1.first==p2.first&&p1.second> res; + for(auto &p:people) + { + res.insert(res.begin()+p.second,p); + } + return res; + } +}; +``` diff --git a/2018.12.20-leetcode406/TheRocket.md b/2018.12.20-leetcode406/TheRocket.md new file mode 100644 index 000000000..fd3e64e74 --- /dev/null +++ b/2018.12.20-leetcode406/TheRocket.md @@ -0,0 +1,15 @@ +```java +class Solution { + public int[][] reconstructQueue(int[][] people) { + Arrays.sort(people, (o1, o2) -> o1[0] != o2[0] ? Integer.compare(o2[0], o1[0]) : Integer.compare(o1[1], o2[1])); + for (int i = 0; i < people.length; ++i) { + int[] p = people[i]; + for (int j = i; j > p[1]; --j) { + people[j] = people[j - 1]; + } + people[p[1]] = p; + } + return people; + } +} +``` diff --git a/2018.12.20-leetcode406/marguerite.md b/2018.12.20-leetcode406/marguerite.md new file mode 100644 index 000000000..0b3bdd235 --- /dev/null +++ b/2018.12.20-leetcode406/marguerite.md @@ -0,0 +1,28 @@ +给出了一些人的身高和这个人前面身高大于等于他的人数,对这些人进行排队,使得所有人的情况都得到满足。这道题的思路是(贪心算法): + +  (1)首先找到身高最高的人并对他们进行排序。 + +  (2)然后找到身高次高的人,按照他们的前面的人数把他们插入到最高的人群中。 + +因此这是一个排序和插入的过程,按照身高进行降序排序,然后把身高相同的人按照k进行升序排序。每次取出身高相同的一组人,按照k值把他们插入到队列中。 + +``` +public class Solution { + public int[][] reconstructQueue(int[][] people) { + Arrays.sort(people, new Comparator() { //按身高降序排序(h大的在前面),按k的大小升序排列(k小的在前面) + public int compare(int[] a, int[] b) { + if(a[0] != b[0]) return -a[0]+b[0]; + else return a[1]-b[1]; + } + }); + + List res=new LinkedList<>(); //保存结果 + + for(int i=0;i() { + @Override + public int compare(int[] o1, int[] o2) { + if (o1[0] == o2[0]) { + return o1[1] - o2[1]; + } + return o2[0] - o1[0]; + } + }); + List list = new ArrayList<>(); + for (int i = 0; i < people.length; i++) { + list.add(people[i][1], new int[]{people[i][0], people[i][1]}); + } + for (int i = 0; i < list.size(); i++) { + people[i][0] = list.get(i)[0]; + people[i][1] = list.get(i)[1]; + } + return people; + } diff --git "a/2018.12.20-leetcode406/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.20-leetcode406/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..a1d5a6cb6 --- /dev/null +++ "b/2018.12.20-leetcode406/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,29 @@ +#### [406. Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) +**题目描述** +> 假设有打乱顺序的一群人站成一个队列。 +每人用一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面即身高≥h的人数。 +编写一个算法来重建这个队列。 + +**例子** +> Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] +Output: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] + +**思想** +**要点**是排序方式。 +1)按照h降序,k升序的方式排列。例子为[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]] +2)首先[7,0], [7,1]正确;对于[6,1]要求前面有一个比它高的,所以在idx=1插入[6,1];对于[5,0],要求前面有没有比它高的,所以在idx=0插入[5,0]... + +**解法** +```python +class Solution(object): + def reconstructQueue(self, people): + """ + :type people: List[List[int]] + :rtype: List[List[int]] + """ + res = [] + people = sorted(people, key = lambda(h, k):(-h, k)) + for p in people: + res.insert(p[1], p) + return res +``` \ No newline at end of file diff --git "a/2018.12.20-leetcode406/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.20-leetcode406/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..7d32755b5 --- /dev/null +++ "b/2018.12.20-leetcode406/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,27 @@ +``` +class Solution { + public int[][] reconstructQueue(int[][] people) { + if(null==people||people.length==0||people[0].length==0){ + return new int[0][0]; + } + Arrays.sort(people,new Comparator(){ + public int compare(int[] a,int[] b){ + if(a[0]==b[0]){ + return a[1]-b[1]; + }else{ + return b[0]-a[0]; + } + } + }); + + for(int i=0;iperson[1];j--){ + people[j] = people[j-1]; + } + people[person[1]] = person; + } + return people; + } +} +``` diff --git "a/2018.12.20-leetcode406/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.20-leetcode406/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..ad62127e8 --- /dev/null +++ "b/2018.12.20-leetcode406/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,22 @@ +``` +bool cmp(pair &p1, pair &p2) +{ + return (p1.first>p2.first)||(p1.first==p2.first && p1.second> reconstructQueue(vector>& people) { + + sort(people.begin(), people.end(), cmp); + + vector> ret; + for(auto it:people) + { + ret.insert(ret.begin() + it.second, it); + } + + return ret; + } +}; +``` diff --git "a/2018.12.21-leetcode763/763. \345\210\222\345\210\206\345\255\227\346\257\215\345\214\272\351\227\264.md" "b/2018.12.21-leetcode763/763. \345\210\222\345\210\206\345\255\227\346\257\215\345\214\272\351\227\264.md" new file mode 100644 index 000000000..13b467743 --- /dev/null +++ "b/2018.12.21-leetcode763/763. \345\210\222\345\210\206\345\255\227\346\257\215\345\214\272\351\227\264.md" @@ -0,0 +1,15 @@ +字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。 +返回一个表示每个字符串片段的长度的列表。 + +示例 1: + +输入: S = "ababcbacadefegdehijhklij" +输出: [9,7,8] +解释: +划分结果为 "ababcbaca", "defegde", "hijhklij"。 +每个字母最多出现在一个片段中。 +像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。 +注意: + +S的长度在[1, 500]之间。 +S只包含小写字母'a'到'z'。 diff --git a/2018.12.21-leetcode763/Avalon.md b/2018.12.21-leetcode763/Avalon.md new file mode 100644 index 000000000..bab975bc3 --- /dev/null +++ b/2018.12.21-leetcode763/Avalon.md @@ -0,0 +1,39 @@ +class Solution { + public List partitionLabels(String S) { + if (S == null || S.length() == 0) return null; + + List list = new ArrayList<>(); + + //region 开始解题 + //System.out.println('b'-'a');//1-->创建一个二维数组 + ///1.创建一个二维数组,存储起止位置 + int[][] stored = new int[26][];//26个英文字母 + int start, end; + for (int i = 0; i < 26; i++) {//没有时为-1 + start = S.indexOf((char) ('a' + i)); + end = S.lastIndexOf((char) ('a' + i)); + stored[i] = new int[]{start, end}; + } + Stream stream = Arrays.stream(stored);//转换为stream 进行操作 + //stream.forEach(p-> System.out.println(Arrays.toString((int[])p))); + //2.筛选不需要的部分 + 按照 start 位置进行排序 + int[][] tempResult = (int[][]) stream.filter(p -> ((int[]) p)[0] > -1).sorted((e1, e2) -> ((int[]) e1)[0] - ((int[]) e2)[0]).toArray(int[][]::new);//通过流转化为数组 + //3.通过贪婪算法得出结果 + + int j = 1, i = 0;//count=0, + for (; j < tempResult.length; j++) { + if (tempResult[i][1] > tempResult[j][0]) {//结束位置覆盖开始位置-》 + if (tempResult[i][1] < tempResult[j][1]) + tempResult[i][1] = tempResult[j][1]; + } else { + list.add(tempResult[i][1] - tempResult[i][0] + 1); + i = j; + } + } + list.add(tempResult[i][1] - tempResult[i][0] + 1); + //endregion + + + return list; + } +} diff --git a/2018.12.21-leetcode763/Be a fresh man.md b/2018.12.21-leetcode763/Be a fresh man.md new file mode 100644 index 000000000..aa07578a4 --- /dev/null +++ b/2018.12.21-leetcode763/Be a fresh man.md @@ -0,0 +1,120 @@ +## 763_(划分字母区间)Partition Labels +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。
+返回一个表示每个字符串片段的长度的列表。
+__注意__:
+1. S的长度在[1, 500]之间。 +2. S只包含小写字母'a'到'z'。 +### 1.2 输入与输出 +输入: +* string S:带划分的字符串 S + +输出: +* vector< int>:划分为尽可能多的片段, 每个字符串片段的长度的列表 +### 1.3 样例 +#### 1.3.1 样例1 +输入: S = "ababcbacadefegdehijhklij"
+输出: [9,7,8]
+解释:划分结果为 "ababcbaca", "defegde", "hijhklij"。
+每个字母最多出现在一个片段中。像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。 + +## 2 思路描述与代码 +### 2.1 思路描述(一遍扫描+切割法) +说明: +* `vector` data; 是个长度可变的 int 数组,c++里面称为容器 +* data.empty() 判断 data 是否为空 +* `vector` data(26, -1); 初始化一个长度为26的长度可变 int 数组,且所有元素初始化为 -1 + +使用`vector< int>` ans记录最终的划分方案;
+使用`vector` border 记录每个划分字母区间的右边界所处的下标;
+使用`vector` dict(26, -1) 记录每个字符第一次出现的位置;
+```cpp +for( int i = 0; i < S.size(); i++ ){ + if(该字母在之前出现过) + * 合并包括该字母第一次出现位置的区间到当前位置的所有区间; + else 如果未出现则记录其第一次出现位置; + 当前位置作为最后一个字母区间的右边界; +} +找出最多分段的区间右边界后,对其进行切割即可; +``` + +比如输出S = "ababc";
+S[0] = 'a', border = [], dict['a'] = -1, 'a'未出现过, dict['a'] = 0, border = [0];
+S[1] = 'b', border = [0], dict['b'] = -1, 'b'未出现过, dict['a'] = 1, border = [0, 1];
+S[2] = 'a', border = [0, 1], dict['a'] = 0, 'a'出现过, 合并区间, border = [2];
+S[3] = 'b', border = [2], dict['b'] = 1, 'b'出现过, 合并区间, border = [3];
+S[4] = 'c', border = [3], dict['c'] = -1, 'c'出现过, dict['c'] = 4, border = [3, 4];
+然后进行切割,将S = "ababc" 从位置3、4分别切割一刀,划分成 "abab" 与 "c"。 + +### 2.2 代码 +```cpp +//一遍扫描+切割法 +vector partitionLabels(string S) { + vector ans; + int len = S.size(); + //记录每个划分字母区间的右边界所处的下标 + vector border; + //记录字母第一次出现的位置 + vector dict(26, -1); + for( int i = 0; i < len; i++ ){ + //如果该字母在之前出现过 + if(dict[S[i] - 'a'] != -1){ + //合并该字母第一次出现位置到当前位置的所有区间 + while(!border.empty() && dict[S[i] - 'a'] <= border.back()) border.pop_back(); + } + //如果未出现记录位置 + else dict[S[i] - 'a'] = i; + //当前位置作为最后一个字母区间的右边界 + border.push_back(i); + } + //找出最多分段的区间右边界后,对其进行划分即可 + int len_border = border.size(); + ans.push_back(border[0] + 1); + for( int i = 1; i < len_border; i++ ){ + ans.push_back(border[i] - border[i - 1]); + } + return ans; +} +``` +## 3 思考与拓展 +### 3.1 思考 +一遍扫描+切割法利用的是字符第一次出现的位置,也可以利用字符最后一次出现的位置的做为突破点。 +#### 3.1.1 其他方法 +##### 3.1.1.1 两遍扫描法 +首先遍历一遍记录 S 中出现字母的最后一个下标;
+再一遍扫描确认最佳分割方案。 +```cpp +vector partitionLabels(string S) { + vector ans; + int len = S.size(); + vector dict(26, -1); + for( int i = 0; i < len; i++ ){ + dict[S[i] - 'a'] = i; + } + //记录当前分割区间的开始与结束下标 + int interval_start = 0; + int interval_end = -1; + for( int i = 0; i < len; i++ ){ + //扩张右边界 + interval_end = max(interval_end, dict[S[i] - 'a']); + //到达右边界的结束位置了 + if(i == interval_end){ + ans.push_back(interval_end - interval_start + 1); + interval_start = interval_end + 1; + } + } + return ans; +} +``` +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +一遍扫描+切割法|O(n)|O(n),最坏情况与两遍扫描法时间复杂度一致 +两遍扫描法|O(1)|O(n) +#### 3.1.3 难点分析 +1. 选取字母第一次还是最后一次出现的位置作为入手点; +2. 根据什么规则判断到了右边界。 + +### 3.2 拓展 +如果给你的是链表数据呢? diff --git a/2018.12.21-leetcode763/Ostrichcrab.md b/2018.12.21-leetcode763/Ostrichcrab.md new file mode 100644 index 000000000..96422b0fe --- /dev/null +++ b/2018.12.21-leetcode763/Ostrichcrab.md @@ -0,0 +1,20 @@ +``` +class Solution { +public: + vector partitionLabels(string S) { + int size = S.length(); + map d; + for(int i = 0; i < size; i++) d[S[i]] = i; + int start = 0; int end = 0; + vector res; + for(int i = 0; i < size; i++){ + end = end>d[S[i]]?end:d[S[i]]; + if(i == end ){ + res.push_back(end - start + 1); + start = end + 1; + } + } + return res; + } +}; +``` diff --git a/2018.12.21-leetcode763/TheRocket.md b/2018.12.21-leetcode763/TheRocket.md new file mode 100644 index 000000000..c8d40c805 --- /dev/null +++ b/2018.12.21-leetcode763/TheRocket.md @@ -0,0 +1,23 @@ +```java +class Solution { + public List partitionLabels(String S) { + char[] cs = S.toCharArray(); + // 字符最后一次出现的位置 + int[] last = new int[26]; + for (int i = 0; i < cs.length; ++i) { + last[cs[i] - 'a'] = i; + } + List res = new ArrayList<>(); + int start = 0; // 区间起始位置 + int end = 0; // 区间结束位置 + for (int i = 0; i < cs.length; ++i) { + end = Math.max(end, last[cs[i] - 'a']); + if (i == end) { + res.add(end - start + 1); + start = i + 1; + } + } + return res; + } +} +``` diff --git a/2018.12.21-leetcode763/WYJ.md b/2018.12.21-leetcode763/WYJ.md new file mode 100644 index 000000000..cb84ec18d --- /dev/null +++ b/2018.12.21-leetcode763/WYJ.md @@ -0,0 +1,20 @@ +```java +class Solution { + public List partitionLabels(String S) { + int[] end = new int[256]; + for(int i = 0; i < S.length(); i++){ + end[S.charAt(i)] = i; + } + int j = 0, anchor = 0; + List res = new ArrayList<>(); + for(int i = 0; i < S.length(); i++){ + j = Math.max(j, end[S.charAt(i)]); + if(j == i){ + res.add(i - anchor + 1); + anchor = i + 1; + } + } + return res; + } +} +``` diff --git a/2018.12.21-leetcode763/sourcema.md b/2018.12.21-leetcode763/sourcema.md new file mode 100644 index 000000000..98209cefa --- /dev/null +++ b/2018.12.21-leetcode763/sourcema.md @@ -0,0 +1,22 @@ +# LeetCode 763 + class Solution { + public List partitionLabels(String S) { + //先找到首字母最后出现的位置,然后遍历从首字母第一次出现到最后一次出现之间的位置, + // 看是否有元素最后出现的位置超过首字母最后出现的位置,如果有更新最后出现的位置下标,如果没有这段区间可以划分为一个段,重复以上步骤即可得到最终结果。 + if (S == null || S.length() == 0) { + return new ArrayList(); + } + List list = new ArrayList<>(); + for (int i = 0; i < S.length();) { + int index = S.lastIndexOf(S.charAt(i)); + for (int j = i+1; j < index; j++) { + if (S.lastIndexOf(S.charAt(j)) > index) { + index=S.lastIndexOf(S.charAt(j)); + } + } + list.add(index - i + 1); + i=index+1; + } + return list; + } +} diff --git "a/2018.12.21-leetcode763/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.21-leetcode763/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..a8eb09aed --- /dev/null +++ "b/2018.12.21-leetcode763/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,55 @@ +#### [763. Partition Labels](https://leetcode.com/problems/partition-labels/) +**题目描述** +> 字符串S只包含小写字母。想把字符串拆成尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。 + +**例子** +> Input: S = "ababcbacadefegdehijhklij" +Output: [9,7,8] +**Explanation:** +The partition is "ababcbaca", "defegde", "hijhklij". +This is a partition so that each letter appears in at most one part. +A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts. + +**思想** +贪心! +遍历S,记录每一个字符的最大索引~ + +**解法** +暴力,时间复杂度O(n^2) +```python +class Solution(object): + def partitionLabels(self, S): + """ + :type S: str + :rtype: List[int] + """ + res = [] + start = end = 0 + for i, c in enumerate(S): + end = max(end, S.rfind(c)) + if i == end: + res.append(end - start + 1) + start = end + 1 + return res +``` +改进:首先用字典记录每个字符的最大索引。时间复杂度O(n),空间复杂度O(n)。 +```python +class Solution(object): + def partitionLabels(self, S): + """ + :type S: str + :rtype: List[int] + """ + dic = {} + for i, c in enumerate(S): + dic[c] = i + + res = [] + start = end = 0 + for i, c in enumerate(S): + end = max(end, dic[c]) + if i == end: + res.append(end - start + 1) + start = end + 1 + return res +``` \ No newline at end of file diff --git "a/2018.12.21-leetcode763/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.21-leetcode763/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..2a2b9149c --- /dev/null +++ "b/2018.12.21-leetcode763/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,28 @@ +``` +class Solution { + public List partitionLabels(String S) { + List res = new ArrayList<>(); + int len = S.length(); + int[] last = new int[26]; + + //保存最后位置 + for(int i=0;i& flowerbed, int n) { + int tmp = 0; + int size = flowerbed.size(); + if(size == 0 && n!= 0) return false; + if(size == 0 && n==0)return true; + if(size == 1 && n>1) return false; + if(size == 1 && n==1){ + if(flowerbed[0]==0) return true; + else return false; + } + if(flowerbed[1]==0 && flowerbed[0]==0) { + tmp++; + flowerbed[0]=1; + } + if(flowerbed[size-2]==0 && flowerbed[size-1]==0){ + tmp++; + flowerbed[size-1]=1; + } + for(int i = 1; i < size -1; i++){ + if(flowerbed[i-1]==0 && flowerbed[i+1]==0 && flowerbed[i]==0){ + tmp++; + flowerbed[i] = 1; + } + } + if(tmp>=n)return true; + else return false; + } +}; +``` diff --git a/2018.12.22-leetcode605/TheRocket.md b/2018.12.22-leetcode605/TheRocket.md new file mode 100644 index 000000000..dc218ea07 --- /dev/null +++ b/2018.12.22-leetcode605/TheRocket.md @@ -0,0 +1,21 @@ +```java +class Solution { + public boolean canPlaceFlowers(int[] flowerbed, int n) { + int len = flowerbed.length; + if (len < 2 * n - 1) { + return false; + } + for (int i = 0; i < len && n > 0; ) { + int next = i + 1 < len ? flowerbed[i + 1] : 0; + if (flowerbed[i] == 0 && next == 0) { + --n; + i += 2; + } else { + while (++i < len && flowerbed[i] == 1) {} + ++i; + } + } + return n == 0; + } +} +``` diff --git a/2018.12.22-leetcode605/Tony the Cyclist.md b/2018.12.22-leetcode605/Tony the Cyclist.md new file mode 100644 index 000000000..81cd0615f --- /dev/null +++ b/2018.12.22-leetcode605/Tony the Cyclist.md @@ -0,0 +1,53 @@ +```python +class Solution(object): + def canPlaceFlowers(self, flowerbed, n): + """ + :type flowerbed: List[int] + :type n: int + :rtype: bool + """ + cot = 0 + if 0 not in flowerbed: + return 0 == n + if len(flowerbed) == 1: + if flowerbed[0] == 0: + return 0 <= n + else: + return 0 == n + if 1 not in flowerbed: + num = len(flowerbed) + 2 + if num % 2 != 0: + cot += num / 2 + else: + cot += num / 2 - 1 + if cot >= n: + return True + else: + return False + start = flowerbed.index(0) + res = [] + for i in range(len(flowerbed)): + if flowerbed[i] == 1: + tmp = flowerbed[start: i] + if start == 0: + tmp = [0] + tmp + res.append(tmp) + start = i + 1 + if i == len(flowerbed)-1: + tmp = flowerbed[start: ] + tmp = tmp + [0] + res.append(tmp) + print res + for i in range(len(res)): + if len(res[i]) == 0: + continue + elif len(res[i]) % 2 == 0: + cot += len(res[i]) / 2 - 1 + else: + cot += len(res[i]) / 2 + print cot + if cot >= n: + return True + else: + return False +``` diff --git a/2018.12.22-leetcode605/WYJ.md b/2018.12.22-leetcode605/WYJ.md new file mode 100644 index 000000000..0db176d6a --- /dev/null +++ b/2018.12.22-leetcode605/WYJ.md @@ -0,0 +1,36 @@ +```java +class Solution { + public boolean canPlaceFlowers(int[] flowerbed, int n) { + for(int i = 0; i < flowerbed.length; i++){ + if(n == 0){ + return true; + } + if(flowerbed[i] == 0){ + if(i - 1 < 0){ + if(i + 1 < flowerbed.length&&flowerbed[i + 1] == 0){ + flowerbed[i] = 1; + n--; + } + if(i + 1 >= flowerbed.length){ + flowerbed[i] = 1; + n--; + } + } + else if(i + 1 == flowerbed.length){ + if(i - 1 >= 0&&flowerbed[i - 1] == 0){ + flowerbed[i] = 1; + n--; + } + } + else{ + if(flowerbed[i - 1] == 0&&flowerbed[i + 1] == 0){ + flowerbed[i] = 1; + n--; + } + } + } + } + return n == 0; + } +} +``` diff --git a/2018.12.22-leetcode605/sourcema.md b/2018.12.22-leetcode605/sourcema.md new file mode 100644 index 000000000..5371b716e --- /dev/null +++ b/2018.12.22-leetcode605/sourcema.md @@ -0,0 +1,31 @@ +# LeetCode 605 + class Solution { + public boolean canPlaceFlowers(int[] flowerbed, int n) {//对每个位置为0的元素,考虑元素相邻位置是不是都为0,如果为0符合条件,如果不为0跳过该位置考虑下一个位置,两端单独考虑。 + if (flowerbed == null || flowerbed.length == 0||n<0) { + return false; + } + if (n == 0) { + return true; + } + if (n == 1 && flowerbed.length == 1 && flowerbed[0] == 0) { + return true; + } + if (flowerbed[0] == 0 && flowerbed.length > 1 && flowerbed[1] == 0) { + flowerbed[0]=1; + n--; + } + for (int i = 1; i < flowerbed.length-1; i++) { + if (n == 0) { + break; + } + if (flowerbed[i] == 0 && flowerbed[i - 1] == 0 && flowerbed[i + 1] == 0) { + flowerbed[i]=1; + n--; + } + } + if (n!=0&&flowerbed.length > 1 && flowerbed[flowerbed.length - 1] == 0 && flowerbed[flowerbed.length - 2] == 0) { + n--; + } + return n==0; + } +} diff --git "a/2018.12.22-leetcode605/\345\274\240\345\260\217\350\203\226.md" "b/2018.12.22-leetcode605/\345\274\240\345\260\217\350\203\226.md" new file mode 100644 index 000000000..eb3eae706 --- /dev/null +++ "b/2018.12.22-leetcode605/\345\274\240\345\260\217\350\203\226.md" @@ -0,0 +1,19 @@ + class Solution { + public: + bool canPlaceFlowers(vector& flowerbed, int n) { + int count = 0; + if (flowerbed.size() == 0) return false; + if (flowerbed.size() == 1 && flowerbed[0] == 0) return true; + for (int i = 0; i < flowerbed.size() && n > 0; i++){ + if (flowerbed[i] == 0){ + if (i == 0 || i == flowerbed.size()-1) count++; + count++; + }else{ + n -= (count-1)/2; + count = 0; + } + } + n -= (count-1)/2; + return n <=0; + } + }; diff --git "a/2018.12.22-leetcode605/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.22-leetcode605/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..8641a39c8 --- /dev/null +++ "b/2018.12.22-leetcode605/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,65 @@ +#### [605. Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) +**题目描述** +> 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。 +但花不能种植在相邻的地块上,因为它们会争夺水源,两者都会死去。 + +> 给定一个只包含0和1的花坛数组(其中0表示没种花,1表示种了花),和一个数n 。 +问能否在不打破种植规则的情况下种n朵花? + +**例子** +> **Example 1:** +Input: flowerbed = [1,0,0,0,1], n = 1 +Output: True + +> **Example 2:** +Input: flowerbed = [1,0,0,0,1], n = 2 +Output: False + +**思想** +统计连续0的数量 +1)开头/结尾,连续2/3 —— 种1个;连续4/5 —— 种2个;... +2)连续3/4个 —— 种1个;连续5/6个 —— 种2个;... + +Trick:对开头和结尾进行填充 + +**解法** +```python +class Solution(object): + def canPlaceFlowers(self, flowerbed, n): + """ + :type flowerbed: List[int] + :type n: int + :rtype: bool + """ + cnt = 0 + zero = 1 + for f in flowerbed: + if f == 0: + zero += 1 + else: + cnt += (zero - 1) // 2 + zero = 0 + if zero: # Tail + cnt += zero // 2 + return n <= cnt +``` +改进。预填充flowerbed +```python +class Solution(object): + def canPlaceFlowers(self, flowerbed, n): + """ + :type flowerbed: List[int] + :type n: int + :rtype: bool + """ + flowerbed = [1, 0] + flowerbed + [0, 1] + + cnt = zero = 0 + for f in flowerbed: + if f == 0: + zero += 1 + elif zero > 0: + cnt += (zero - 1)//2 + zero = 0 + return n <= cnt +``` \ No newline at end of file diff --git "a/2018.12.22-leetcode605/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.22-leetcode605/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..b7ce57867 --- /dev/null +++ "b/2018.12.22-leetcode605/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,16 @@ +``` +class Solution { + public boolean canPlaceFlowers(int[] flowerbed, int n) { + int i=0,count = 0; + while(i=n; + } +} +``` diff --git "a/2018.12.23-leetcode392/392. \345\210\244\346\226\255\345\255\220\345\272\217\345\210\227.md" "b/2018.12.23-leetcode392/392. \345\210\244\346\226\255\345\255\220\345\272\217\345\210\227.md" new file mode 100644 index 000000000..eee90e959 --- /dev/null +++ "b/2018.12.23-leetcode392/392. \345\210\244\346\226\255\345\255\220\345\272\217\345\210\227.md" @@ -0,0 +1,21 @@ +给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 + +你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 + +字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。 +(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 + +示例 1: +s = "abc", t = "ahbgdc" + +返回 true. + +示例 2: +s = "axc", t = "ahbgdc" + +返回 false. + +后续挑战 : + +如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。 +在这种情况下,你会怎样改变代码? diff --git a/2018.12.23-leetcode392/Be a fresh man.md b/2018.12.23-leetcode392/Be a fresh man.md new file mode 100644 index 000000000..e30299ac8 --- /dev/null +++ b/2018.12.23-leetcode392/Be a fresh man.md @@ -0,0 +1,77 @@ +## 392_(判断子序列)Is Subsequence +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
+你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
+字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 + +__后续挑战__ :
+如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码? + +### 1.2 输入与输出 +输入: +* string s:给定的字符串 s +* string t:给定的字符串 t + +输出: +* bool:判断 s 是否为 t 的子序列 +### 1.3 样例 +#### 1.3.1 样例1 +输入: s = "abc", t = "ahbgdc"
+输出: true +#### 1.3.2 样例2 +输入: s = "axc", t = "ahbgdc"
+输出: false +## 2 思路描述与代码 +### 2.1 思路描述(双下标法) +i为字符 s 的遍历下标, j 表示字符 t 的遍历下标 +```cpp +for( j = 0; j < len_t; j++ ){ + if(s[i] == t[j]){ + if(i == len_s - 1) return true; + else i++; + } +} +``` +比如输入: s = "abc", t = "ahbgdc";
+j = 0, i = 0, s[0] == t[0], i = 1;
+j = 1, i = 1, s[1] != t[1];
+j = 2, i = 1, s[1] == t[2], i = 2;
+j = 3, i = 2, s[1] != t[3];
+j = 4, i = 2, s[2] != t[4];
+j = 5, i = 2, s[2] == t[5], 返回true; +### 2.2 代码 +```cpp +bool isSubsequence(string s, string t) { + int len_s = s.size(); + int len_t = t.size(); + //边界情况 + if(len_s > len_t) return false; + else if(len_s == 0) return true; + + //遍历t + int i = 0, j = 0; + for( j = 0; j < len_t; j++ ){ + //如果当前字符相等,查找 s 的下一个字符是否在 t 中 + if(s[i] == t[j]){ + if(i == len_s - 1) return true; + else i++; + } + } + return false; +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题按照子序列的定义并利用双下标法可以很容易解决。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +双下标法|O(1)|O(s_len+t_len) +#### 3.1.3 难点分析 +1. i下标的更新。 + +### 3.2 拓展 +如果给你的是数组数据呢? diff --git a/2018.12.23-leetcode392/FFFro.md b/2018.12.23-leetcode392/FFFro.md new file mode 100644 index 000000000..d33f0a9d4 --- /dev/null +++ b/2018.12.23-leetcode392/FFFro.md @@ -0,0 +1,25 @@ +class Solution { + public boolean isSubsequence(String s, String t) { + char[] tempS = s.toCharArray(); + char[] tempT = t.toCharArray(); + int s_l = tempS.length; + int t_l = tempT.length; + + if (s_l > t_l) { + return false; + } else if (s_l == 0) { + return true; + } + int i = 0; + for (int j = 0; j < t_l; j++) { + if (tempS[i] == tempT[j]) { + if (i == s_l - 1) { + return true; + } else { + i++; + } + } + } + return false; + } +} diff --git a/2018.12.23-leetcode392/Ostrichcrab.md b/2018.12.23-leetcode392/Ostrichcrab.md new file mode 100644 index 000000000..b9b095f51 --- /dev/null +++ b/2018.12.23-leetcode392/Ostrichcrab.md @@ -0,0 +1,20 @@ +``` +class Solution { +public: + bool isSubsequence(string s, string t) { + int ls = s.length(); + int lt = t.length(); + int i =0; int j = 0; + for(; i!=ls&&j!=lt;){ + if(s[i]==t[j]){ + i++; + j++; + }else{ + j++; + } + } + if(i==ls) return true; + else return false; + } +}; +``` diff --git a/2018.12.23-leetcode392/TheRocket.md b/2018.12.23-leetcode392/TheRocket.md new file mode 100644 index 000000000..d214cbf21 --- /dev/null +++ b/2018.12.23-leetcode392/TheRocket.md @@ -0,0 +1,16 @@ +```java +class Solution { + public boolean isSubsequence(String s, String t) { + int index = -1; + for (char c : s.toCharArray()) { + // 每次从下一个位置开始找 + index = t.indexOf(c, index + 1); + // 没找到 + if (index == -1) { + return false; + } + } + return true; + } +} +``` diff --git a/2018.12.23-leetcode392/Tony the Cyclist.md b/2018.12.23-leetcode392/Tony the Cyclist.md new file mode 100644 index 000000000..c5ebc9045 --- /dev/null +++ b/2018.12.23-leetcode392/Tony the Cyclist.md @@ -0,0 +1,20 @@ +```python +class Solution(object): + def isSubsequence(self, s, t): + """ + :type s: str + :type t: str + :rtype: bool + """ + if len(s) == 0: + return True + if len(s) > len(t): + return False + index = 0 + for i in range(len(t)): + if t[i] == s[index]: + index += 1 + if index == len(s): + return True + return False +``` diff --git a/2018.12.23-leetcode392/WYJ.md b/2018.12.23-leetcode392/WYJ.md new file mode 100644 index 000000000..c7e7076da --- /dev/null +++ b/2018.12.23-leetcode392/WYJ.md @@ -0,0 +1,20 @@ +```java +class Solution { + public boolean isSubsequence(String s, String t) { + if(s.length() == 0){ + return true; + } + int indexS = 0, indexT = 0; + while(indexT < t.length()){ + if(t.charAt(indexT) == s.charAt(indexS)){ + indexS++; + } + indexT++; + if(indexS == s.length()){ + return true; + } + } + return false; + } +} +``` diff --git a/2018.12.23-leetcode392/lyan_dut.md b/2018.12.23-leetcode392/lyan_dut.md new file mode 100644 index 000000000..cbd34cf80 --- /dev/null +++ b/2018.12.23-leetcode392/lyan_dut.md @@ -0,0 +1,21 @@ +```c++ +/* + * 392. 判断子序列 + * https://leetcode-cn.com/problems/is-subsequence/ + */ +/* + * 方法一: 双指针 + */ +bool MyLeetCode::isSubsequence(string s, string t) { + if(s.length()==0 && t.length()==0) + return true; + for(int i=0, j=0; j < t.length(); j++){ + if(s[i] == t[j]) + i++; + if(i==s.length()) + return true; + } + return false; +} + +``` diff --git a/2018.12.23-leetcode392/sourcema.md b/2018.12.23-leetcode392/sourcema.md new file mode 100644 index 000000000..ed3a69bf2 --- /dev/null +++ b/2018.12.23-leetcode392/sourcema.md @@ -0,0 +1,21 @@ +# leetcode 392 + class Solution { + public boolean isSubsequence(String s, String t) {//依次比较s和t中的元素是否相等 + if (s == null ||t==null) { + return false; + } + if (s.length() == 0) { + return true; + } + int j=0; + for (int i =0; i 给定字符串s和字符串t,判断s是否是t的子序列。 + +> 子序列:删除原始字符串的某些字符,不改变相对位置顺序。(例如,"ace" 是"abcde" 的子串,而 "aec" 不是) +假设s和t中只有小写英文字母,len(t) <= 500000且len(s) <= 100 + +**例子** +> **Example 1:** +s = "abc", t = "ahbgdc" +Return true. + +> **Example 2:** +s = "axc", t = "ahbgdc" +Return false. + +**思想** +双下标法 + +**解法** +```python +class Solution(object): + def isSubsequence(self, s, t): + """ + :type s: str + :type t: str + :rtype: bool + """ + i = j = 0 + while i < len(s) and j < len(t): + while j < len(t) and s[i] != t[j]: + j += 1 + if j == len(t): + break + i += 1 + j += 1 + return i == len(s) +``` +简洁 +```python +class Solution(object): + def isSubsequence(self, s, t): + """ + :type s: str + :type t: str + :rtype: bool + """ + if not s: + return True + + idx = 0 + for c in t: + if s[idx] == c: + idx += 1 + if idx == len(s): + return True + return False +``` \ No newline at end of file diff --git "a/2018.12.24-leetcode665/665. \351\235\236\351\200\222\345\207\217\346\225\260\345\210\227.md" "b/2018.12.24-leetcode665/665. \351\235\236\351\200\222\345\207\217\346\225\260\345\210\227.md" new file mode 100644 index 000000000..9b2a2913c --- /dev/null +++ "b/2018.12.24-leetcode665/665. \351\235\236\351\200\222\345\207\217\346\225\260\345\210\227.md" @@ -0,0 +1,20 @@ +``` +给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。 + +我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。 + +**示例 1:** + +输入: [4,2,3] +输出: True +解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。 + + +**示例 2:** + +输入: [4,2,1] +输出: False +解释: 你不能在只改变一个元素的情况下将其变为非递减数列。 + +说明: n 的范围为 [1, 10,000]。 +``` diff --git a/2018.12.24-leetcode665/Be a fresh man.md b/2018.12.24-leetcode665/Be a fresh man.md new file mode 100644 index 000000000..e2c615afb --- /dev/null +++ b/2018.12.24-leetcode665/Be a fresh man.md @@ -0,0 +1,62 @@ +## 665_(非递减数列)Non-decreasing Array +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。
+我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。
+__说明__:
+n 的范围为 [1, 10,000]。 +### 1.2 输入与输出 +输入: +* vector& nums:输入的整数数组 + +输出: +* bool:在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列 +### 1.3 样例 +#### 1.3.1 样例1 +输入: [4,2,3]
+输出: True
+解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。 +#### 1.3.2 样例2 +输入: [4,2,1]
+输出: False
+解释: 你不能在只改变一个元素的情况下将其变为非递减数列。 +## 2 思路描述与代码 +### 2.1 思路描述(比较计数法) +cnt统计当前数比前一个数小的个数; +遍历数组中所有的值 +* 如果当前值比前一个值小 + * 如果cnt == 1,则判断是否存在纠正的方式,无则返回false + * 否则cnt >= 2,则不存在纠正方式,返回false +### 2.2 代码 +```cpp +bool checkPossibility(vector& nums) { + int n = nums.size(); + int cnt = 0; + for (int i = 1; i < n; i++) { + if (nums[i - 1] > nums[i]) { + cnt++; + //cnt = 1时,需要注意有两种情况可以补救: + //1. 比如[-1 4 2 3], 4 < 2, 2 > -1, 通过修改 4 为 -1~2 间的数都可以补救 + //2. 比如[1 2 -1 3],-1 < 2, 2 < 3, 通过修改 -1 为 2~3 间的数都可以补救 + + //cnt >= 2则怎样都不行了,因为只能修改一次 + if((cnt == 1 && i >= 2 && i < n - 1 && nums[i] < nums[i - 2] && nums[i + 1] < nums[i - 1]) || cnt >= 2) return false; + } + } + return true; +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题中需要考虑多种情况的可能性,否则容易犯错。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +比较计数法|O(1)|O(n) +#### 3.1.3 难点分析 +1. 当前值比前一个值小只出现一次时需要考虑[-1 4 2 3]、[1 2 -1 3]、[1,2,3,2]、[4,1,2,3]之类可纠正的情况 + +### 3.2 拓展 +如果给你的是链表数据呢? diff --git a/2018.12.24-leetcode665/Ostrichcrab.md b/2018.12.24-leetcode665/Ostrichcrab.md new file mode 100644 index 000000000..4cc72cecc --- /dev/null +++ b/2018.12.24-leetcode665/Ostrichcrab.md @@ -0,0 +1,19 @@ +``` +class Solution { +public: + bool checkPossibility(vector& nums) { + int size = nums.size(); + int res = 0; + for(int i = 1; i < size && res < 2; i++){ + if(nums[i]>=nums[i-1]) continue; + if(i-2>=0 && nums[i] nums[i]) { + if (changed) { + return false; + } + changed = true; + if (i - 2 >= 0 && nums[i - 2] > nums[i]) { + nums[i] = nums[i - 1]; + } else { + nums[i - 1] = nums[i]; + } + } + } + return true; + } +} +``` diff --git a/2018.12.24-leetcode665/Tony the Cyclist.md b/2018.12.24-leetcode665/Tony the Cyclist.md new file mode 100644 index 000000000..b8b651677 --- /dev/null +++ b/2018.12.24-leetcode665/Tony the Cyclist.md @@ -0,0 +1,36 @@ +```java +class Solution { + public boolean checkPossibility(int[] nums) { + if(nums.length < 2){ + return true; + } + int cot = 0; + int index; + if(nums[0] > nums[1]){ + cot = 1; + } + int len = nums.length - 1; + for (int i = 1; i < len; i ++){ + if (cot > 1){ + return false; + } + if (nums[i] > nums[i+1]){ + if(nums[i-1] >= nums[i+1]){ + nums[i+1] = nums[i]; + + } + else { + nums[i] = nums[i-1]; + } + //len--; + //i--; + cot++; + } + } + if (cot > 1){ + return false; + } + return true; + } +} +``` diff --git a/2018.12.24-leetcode665/WYJ.md b/2018.12.24-leetcode665/WYJ.md new file mode 100644 index 000000000..4694d91b9 --- /dev/null +++ b/2018.12.24-leetcode665/WYJ.md @@ -0,0 +1,49 @@ +```java +class Solution { + public boolean checkPossibility(int[] nums) { + if(nums.length == 0 || nums.length == 1){ + return true; + } + List index = new ArrayList<>(); + for(int i = 0; i < nums.length - 1; i++){ + if(nums[i] > nums[i + 1]){ + if(i == 0){ + index.add(new int[]{i, nums[i + 1]}); + } + else if(nums[i - 1] > nums[i + 1]){ + //index.add(new int[]{i, nums[i + 1]}); + index.add(new int[]{i + 1, nums[i]}); + } + else{ + index.add(new int[]{i, nums[i + 1]}); + } + + } + } + if(index.size() == 0){ + return true; + } + for(int i = 0; i < index.size(); i++){ + int[] nums1 = nums.clone(); + int[] change = index.get(i); + for(int j = 0; j < nums1.length; j++){ + if(j == change[0]){ + nums1[j] = change[1]; + } + } + if(isNonde(nums1)){ + return true; + } + } + return false; + } + public boolean isNonde(int[] nums){ + for(int i = 0; i < nums.length - 1; i++){ + if(nums[i] > nums[i + 1]){ + return false; + } + } + return true; + } +} +``` diff --git a/2018.12.24-leetcode665/sourcema.md b/2018.12.24-leetcode665/sourcema.md new file mode 100644 index 000000000..3cd7f5a9f --- /dev/null +++ b/2018.12.24-leetcode665/sourcema.md @@ -0,0 +1,29 @@ +# leetcode 665 + class Solution { + public boolean checkPossibility(int[] nums) { + if (nums == null || nums.length == 0||nums.length==1) { + return true; + } + boolean flag=false; + boolean visited=false; + for (int i = 1; i = 0 && nums[i] < nums[i - 2]) { + return false; + } + } + flag = true; + } else { + flag=false; + break; + } + visited=true; + } + } + return !visited?true:flag; + } +} diff --git "a/2018.12.24-leetcode665/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" "b/2018.12.24-leetcode665/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" new file mode 100644 index 000000000..42bba4068 --- /dev/null +++ "b/2018.12.24-leetcode665/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" @@ -0,0 +1,17 @@ +class Solution { + public boolean checkPossibility(int[] nums) { + int cnt = 0; + for(int i = 1; i <= nums.length - 1 ; i++) { + if(nums[i-1] > nums[i]) { + if(i-2 < 0 || nums[i-2] < nums[i]) { + nums[i-1] = nums[i]; + } else { + nums[i] = nums[i-1]; + } + cnt++; + } + } + if(cnt <= 1) return true; + return false; + } +} diff --git "a/2018.12.24-leetcode665/\345\246\256\345\217\257.md" "b/2018.12.24-leetcode665/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..21756d46d --- /dev/null +++ "b/2018.12.24-leetcode665/\345\246\256\345\217\257.md" @@ -0,0 +1,86 @@ +``` +package sy181229; + +/** + * @author suyuan + *给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下, + *该数组能否变成一个非递减数列。 + +我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n), +满足 array[i] <= array[i + 1]。 + +**示例 1:** + +输入: [4,2,3] +输出: True +解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。 + + +**示例 2:** + +输入: [4,2,1] +输出: False +解释: 你不能在只改变一个元素的情况下将其变为非递减数列。 + +说明: n 的范围为 [1, 10,000]。 + */ +public class leetcode_665非递减数列 +{ + + public static void main(String[] args) + { + //int[] nums =new int[]{1 ,2 ,-1 ,3}; + int[] nums =new int[]{4, 2, 3}; + checkPossibility(nums); + + } + + public static boolean checkPossibility2(int[] nums) + { + int len=nums.length; + int c=0; + for(int i=1;inums[i]) + { + c++; + if((c==1 && i>=2 && i=2) + return false; + } + } + return true; + } + + public static boolean checkPossibility(int[] nums) + { + boolean flag=false; + int len=nums.length; + for(int i=0;i nums[i+1]) + { + if(flag) + return false; + else + { + //找到是前一个数大还是后一个数大 + //[-1 4 2 3] + //后一个大于前一个 复合递增规则,前后不用调整,调整i + //第一个数 -1 会越界 + if(i-1 < 0 || nums[i+1] >= nums[i-1]) + nums[i]=nums[i+1]; + //[1 2 -1 3] + //前一个大于后一个 , 后一个不符合递增规则, 调整后一个 + else + nums[i+1]=nums[i]; + flag=true; + + } + } + } + return true; + } + +} +``` diff --git "a/2018.12.24-leetcode665/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.24-leetcode665/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..7249e32c3 --- /dev/null +++ "b/2018.12.24-leetcode665/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,37 @@ +#### [665. Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) +**题目描述** +> 给定一个n个整数的数组,判断是否可以将其变为非递减数组(最多修改一个元素)。 + +**例子** +> Example 1: +Input: [4,2,3] +Output: True +Explanation: You could modify the first 4 to 1 to get a non-decreasing array. + +> **Example 2:** +Input: [4,2,1] +Output: False +Explanation: You can't get a non-decreasing array by modify at most one element. + +**思想** +首先画一个上升的数组,然后标记只有一个元素Bug时的情况。 +只需比较相邻两个数的大小,保证非递减的数对的个数 <= 1。 +特例 - [3,4,2,3], Modify 2 + +**解法** +```python +class Solution(object): + def checkPossibility(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + cnt = 0 + for i in range(len(nums)-1): + if nums[i] > nums[i+1]: + cnt += 1 + # 特例 - [3,4,2,3], Modify 2 + if cnt == 2 or cnt == 1 and i >= 2 and nums[i] < nums[i-2] and nums[i+1] < nums[i-1]: + return False + return True +``` \ No newline at end of file diff --git "a/2018.12.25-leetcode122/122. \344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272 II.md" "b/2018.12.25-leetcode122/122. \344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272 II.md" new file mode 100644 index 000000000..ada8ac7c5 --- /dev/null +++ "b/2018.12.25-leetcode122/122. \344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272 II.md" @@ -0,0 +1,26 @@ +``` +给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 + +设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 + +注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 + +示例 1: + +输入: [7,1,5,3,6,4] +输出: 7 +解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 + 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。 +示例 2: + +输入: [1,2,3,4,5] +输出: 4 +解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 + 注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。 + 因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。 +示例 3: + +输入: [7,6,4,3,1] +输出: 0 +解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 +``` diff --git a/2018.12.25-leetcode122/Be a fresh man.md b/2018.12.25-leetcode122/Be a fresh man.md new file mode 100644 index 000000000..02a29a649 --- /dev/null +++ b/2018.12.25-leetcode122/Be a fresh man.md @@ -0,0 +1,66 @@ +## 122_(买卖股票的最佳时机 II)Best Time to Buy and Sell Stock II +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
+设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
+注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 +### 1.2 输入与输出 +输入: +* vector& prices:长度可变的价格数组prices + +输出: +* int:所能获取的最大利润 + +### 1.3 样例 +#### 1.3.1 样例1 +输入: [7,1,5,3,6,4]
+输出: 7
+解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 + 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。 +#### 1.3.2 样例2 +输入: [1,2,3,4,5]
+输出: 4
+解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 + 注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。 + 因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。 +#### 1.3.3 样例3 +输入: [7,6,4,3,1]
+输出: 0
+解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 + + +## 2 思路描述与代码 +### 2.1 思路描述(贪心法) +把所有可能获利的交易都吃掉,局部最优可以获得全局最优。
+算差分数组,把差分数组中所有为正的元素都加起来就是最大收益。 + +比如输入: [7,1,5,3,6,4]
+差分数组为:[0,-6,4,-2,3,-2]
+最大收益为 4 + 3 = 7 +### 2.2 代码 +```cpp +//函数中涉及到的c++知识 +//vector 是个长度可变的 int 数组,c++里面称为容器 +int maxProfit(vector& prices) { + int len = prices.size(); + int max_profit = 0; + for( int i = 1; i < len; i++ ){ + if(prices[i] - prices[i - 1] > 0) max_profit += prices[i] - prices[i - 1]; + } + return max_profit; +} +``` +## 3 思考与拓展 +### 3.1 思考 +典型的贪心法。本题贪心法和开天眼道理很像,比如差分数组为正,则回到前一天买入,下一天突然跌了,我可以回到前一天卖出去。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +贪心法|O(1)|O(n) +#### 3.1.3 难点分析 +1. 差分数组首元素记为0。 + +### 3.2 拓展 +1. [买卖股票的最佳时机 III](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/)。 diff --git a/2018.12.25-leetcode122/Ostrichcrab.md b/2018.12.25-leetcode122/Ostrichcrab.md new file mode 100644 index 000000000..f12504d50 --- /dev/null +++ b/2018.12.25-leetcode122/Ostrichcrab.md @@ -0,0 +1,14 @@ +``` +class Solution { +public: + int maxProfit(vector& prices) { + int size = prices.size(); + if(size == 0) return 0; + int profit = 0; + for(int i = 1; i < size; i++){ + profit += prices[i]>prices[i-1]?prices[i]-prices[i-1]:0; + } + return profit; + } +}; +``` diff --git a/2018.12.25-leetcode122/TheRocket.md b/2018.12.25-leetcode122/TheRocket.md new file mode 100644 index 000000000..8b048567b --- /dev/null +++ b/2018.12.25-leetcode122/TheRocket.md @@ -0,0 +1,13 @@ +```java +class Solution { + public int maxProfit(int[] prices) { + int res = 0; + for (int i = 1; i < prices.length; ++i) { + if (prices[i] > prices[i - 1]) { + res += prices[i] - prices[i - 1]; + } + } + return res; + } +} +``` diff --git a/2018.12.25-leetcode122/Tony the Cyclist.md b/2018.12.25-leetcode122/Tony the Cyclist.md new file mode 100644 index 000000000..36c812849 --- /dev/null +++ b/2018.12.25-leetcode122/Tony the Cyclist.md @@ -0,0 +1,13 @@ +```python +class Solution(object): + def maxProfit(self, prices): + """ + :type prices: List[int] + :rtype: int + """ + profile = 0 + for i in range(1, len(prices)): + if prices[i] > prices[i-1]: + profile += prices[i] - prices[i-1] + return profile +``` diff --git a/2018.12.25-leetcode122/WYJ.md b/2018.12.25-leetcode122/WYJ.md new file mode 100644 index 000000000..8772b0cfa --- /dev/null +++ b/2018.12.25-leetcode122/WYJ.md @@ -0,0 +1,24 @@ +```java +class Solution { + public int maxProfit(int[] prices) { + return reMaxProfit(prices, 0); + } + private int reMaxProfit(int[] prices, int pos){ + if(pos >= prices.length){ + return 0; + } + int profit = 0; + for(int buyDay = pos; buyDay < prices.length; buyDay++){ + int maxProfit = 0; + for(int sellDay = buyDay + 1; sellDay < prices.length; sellDay++){ + if(prices[buyDay] < prices[sellDay]){ + maxProfit = Math.max(maxProfit, prices[sellDay] - prices[buyDay] + reMaxProfit(prices, sellDay + 1)); + } + } + profit = Math.max(maxProfit, profit); + } + return profit; + + } +} +``` diff --git a/2018.12.25-leetcode122/marguerite.md b/2018.12.25-leetcode122/marguerite.md new file mode 100644 index 000000000..8f387edb8 --- /dev/null +++ b/2018.12.25-leetcode122/marguerite.md @@ -0,0 +1,23 @@ + + +``` +public class OneHundredAndTwentyTwo { + + public static int maxProfit(int[] prices) { + int sum = 0; + for(int i = prices.length - 1;i>0;i--) { + if(prices[i] <= prices[i-1]) { + continue; + } else { + sum += prices[i] - prices[i-1]; + } + } + return sum; + } + public static void main(String[] args) { + int[] nums = new int[] {7,6,5,9,1,3}; + System.out.println(maxProfit(nums)); + } +} + +``` diff --git a/2018.12.25-leetcode122/sourcema.md b/2018.12.25-leetcode122/sourcema.md new file mode 100644 index 000000000..1b84f30a9 --- /dev/null +++ b/2018.12.25-leetcode122/sourcema.md @@ -0,0 +1,15 @@ +# LeetCode 122 + class Solution { + public int maxProfit(int[] prices) {//只要有差价就进行交易 + if (prices==null||prices.length==0||prices.length==1) { + return 0; + } + int res=0; + for (int i = 0; i < prices.length-1; i++) { + if (prices[i+1]-prices[i]>0) { + res+=prices[i+1]-prices[i]; + } + } + return res; + } +} diff --git "a/2018.12.25-leetcode122/\345\210\230\346\266\246\346\263\275(capture).md" "b/2018.12.25-leetcode122/\345\210\230\346\266\246\346\263\275(capture).md" new file mode 100644 index 000000000..7d5322cc6 --- /dev/null +++ "b/2018.12.25-leetcode122/\345\210\230\346\266\246\346\263\275(capture).md" @@ -0,0 +1,34 @@ +```java + public static int maxProfit(int[] prices) { + + int profit=0; + int buyPosition=0; + boolean isbuy = false; //还没有买入 + + for (int i=0;i=prices[i+1]){ + + isbuy=false; + profit=profit+(prices[i]-prices[buyPosition]); + continue; + } + if (i==prices.length-2&&isbuy){ + return profit+(prices[prices.length-1]-prices[buyPosition]); + } + + continue; + + } + + return profit; + } +``` diff --git "a/2018.12.25-leetcode122/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" "b/2018.12.25-leetcode122/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" new file mode 100644 index 000000000..61d3a7cac --- /dev/null +++ "b/2018.12.25-leetcode122/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" @@ -0,0 +1,11 @@ +class Solution { + public int maxProfit(int[] prices) { + int res = 0; + for(int i = 1; i < prices.length; i++){ + if(prices[i] > prices[i-1]){ + res += prices[i] - prices[i-1]; + } + } + return res; + } +} diff --git "a/2018.12.25-leetcode122/\345\217\245\345\255\220.md" "b/2018.12.25-leetcode122/\345\217\245\345\255\220.md" new file mode 100644 index 000000000..6e3b88b7c --- /dev/null +++ "b/2018.12.25-leetcode122/\345\217\245\345\255\220.md" @@ -0,0 +1,13 @@ +```c++ +class Solution { +public: + int maxProfit(vector& prices) { + int get=0; + for(int i=1;iprices[i-1]) + get+=prices[i]-prices[i-1]; + } + return get; + } +}; +``` diff --git "a/2018.12.25-leetcode122/\345\246\256\345\217\257.md" "b/2018.12.25-leetcode122/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..7fcf8f5d8 --- /dev/null +++ "b/2018.12.25-leetcode122/\345\246\256\345\217\257.md" @@ -0,0 +1,56 @@ +``` +package sy181230; + +/** + * @author suyuan + *给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 + +设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 + +注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 + +示例 1: + +输入: [7,1,5,3,6,4] +输出: 7 +解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 + 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。 +示例 2: + +输入: [1,2,3,4,5] +输出: 4 +解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 + 注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。 + 因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。 +示例 3: + +输入: [7,6,4,3,1] +输出: 0 +解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 + */ +public class leetcode_122买卖股票的最佳时机II +{ + + public static void main(String[] args) + { + int[] prices=new int[]{7,1,5,3,6,4}; + System.out.println(maxProfit(prices)); + + } + + //一直贪呀 + public static int maxProfit(int[] prices) + { + if(prices == null || prices.length<2) + return 0; + int max=0; + for(int i=1;iprices[i-1]) + max+=prices[i]-prices[i-1]; + } + return max; + } + +} +``` diff --git "a/2018.12.25-leetcode122/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.25-leetcode122/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..96dce3bfa --- /dev/null +++ "b/2018.12.25-leetcode122/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,43 @@ +#### [122. Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) +**题目描述** +> 给定一个数组,它的第 i 个元素是给定股票第 i 天的价格。 +设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 + +> 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 + +**例子** +> **Example 1:** +Input: [7,1,5,3,6,4] +Output: 7 +Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. + Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. + +> **Example 2:** +Input: [1,2,3,4,5] +Output: 4 +Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. + Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are + engaging multiple transactions at the same time. You must sell before buying again. + +> **Example 3:** +Input: [7,6,4,3,1] +Output: 0 +Explanation: In this case, no transaction is done, i.e. max profit = 0. + +**思想** +可以进行多次交易。所以只要卖出的价格比买进的高,都想卖出,且想以最高价卖出。 +此时我们来看[1,2,3,4,5],在price=1买入,price=5卖出;等价于(5-4)+(4-3)+(3-2)+(2-1)。所以只要次日比前日价格高,我们就进行卖出交易,最终利润可以最大化。 + +**解法** +```python +class Solution(object): + def maxProfit(self, prices): + """ + :type prices: List[int] + :rtype: int + """ + res = 0 + for i in range(len(prices)-1): + res += max(prices[i+1] - prices[i], 0) + return res +``` \ No newline at end of file diff --git "a/2018.12.25-leetcode122/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.25-leetcode122/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..2668bfe62 --- /dev/null +++ "b/2018.12.25-leetcode122/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,14 @@ +``` +class Solution { + public int maxProfit(int[] prices) { + int profit = 0; + boolean buy = false; + for(int i=0;i +__进阶__: +如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 + +### 1.2 输入与输出 +输入: +* vector< int>& nums:给定的整数数组 nums + +输出: +* int:最大子序和 + +### 1.3 样例 +#### 1.3.1 样例1 +输入: [-2,1,-3,4,-1,2,1,-5,4],
+输出: 6
+解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 + +## 2 思路描述与代码 +### 2.1 思路描述(在线处理法) +其思想是如果当前累加的和 this_sum < 0,那么其肯定不会使得后续的子序和更大,所以累加值 this_sum 置 0 重新累加。 +```cpp +len_nums 为输入数组的长度 +max_sum 为记录的最大和 +this_sum 记录当前累加的结果 +for( i = 0; i < len_nums; i++ ){ + this_sum += nums[i]; + max_sum = max(max_sum, this_sum); + if(this_sum < 0) this_sum = 0; +} +``` +### 2.2 代码 +```cpp +class Solution { +public: + const int MIN = -2147483648; + int maxSubArray(vector& nums) { + return maxSubArray_online_processing(nums); + } + //在线处理 + int maxSubArray_online_processing(const vector& nums){ + int len_nums = nums.size(); + int max_sum = MIN; + int this_sum = 0; + for( int i = 0; i < len_nums; i++ ){ + this_sum += nums[i]; + max_sum = max(max_sum, this_sum); + if(this_sum < 0) this_sum = 0; + } + return max_sum; + } +}; +``` +## 3 思考与拓展 +### 3.1 思考 +在线处理的时间复杂度为O(n),此外还有一种方法叫做分治,其空间复杂度为O(nlogn),二者的思想都值得细细回味。 +#### 3.1.1 其他方法 +##### 3.1.1.1 分治法 +分治主要有两个步骤,分和治。
+把输入的 nums 数组一分为2,递归求左半部分最大子序和 left_max,递归求右半部分的最大子序和right_max,一遍扫描求跨越中间节点的最大子序和 across_mid_max,三者的最大值即为最大子序和。 +```cpp +class Solution { +public: + const int MIN = -2147483648; + int maxSubArray(vector& nums) { + return maxSubArray_divideAndConquer(nums, 0, nums.size() - 1); + } + int maxSubArray_divideAndConquer(const vector& nums, const int start, const int end){ + if(start == end) return nums[start]; + int mid = (start + end) / 2; + //获取左、右部分最大值 + int left_max = maxSubArray_divideAndConquer(nums, start, mid); + int right_max = maxSubArray_divideAndConquer(nums, mid + 1, end); + //获取中间最大值 + int left_across_mid_max = MIN; + int left_across_mid_sum = 0; + for( int i = mid; i >= start; i-- ){ + left_across_mid_sum += nums[i]; + left_across_mid_max = max(left_across_mid_max, left_across_mid_sum); + } + int right_across_mid_max = MIN; + int right_across_mid_sum = 0; + for( int i = mid + 1; i <= end; i++ ){ + right_across_mid_sum += nums[i]; + right_across_mid_max = max(right_across_mid_max, right_across_mid_sum); + } + int across_mid_max = left_across_mid_max + right_across_mid_max; + return max(left_max, max(right_max, across_mid_max)); + } +}; +``` + +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +在线处理法|O(1)|O(n) +分治法|O(n)|O(nlogn) +#### 3.1.3 难点分析 +1. 在线处理法需要理解如果当前累加的和 this_sum < 0,那么其肯定不会使得后续的子序和更大; +2. 分治法需要考虑三种可能的最大子列和情况 + +### 3.2 拓展 +本题可以有很多变形,可以尝试[最小子序列和](https://blog.csdn.net/u011493189/article/details/52409375)。 diff --git a/2018.12.26-leetcode53/Ostrichcrab.md b/2018.12.26-leetcode53/Ostrichcrab.md new file mode 100644 index 000000000..83aa24bf9 --- /dev/null +++ b/2018.12.26-leetcode53/Ostrichcrab.md @@ -0,0 +1,17 @@ +``` +class Solution { +public: + int maxSubArray(vector& nums) { + int size = nums.size(); + vector dp(size+1); + dp[0] = nums[0]; + int ans = nums[0]; + for(int i = 1; i0) dp[i]=nums[i]+dp[i-1]; + else dp[i] = nums[i]; + ans = max(ans,dp[i]); + } + return ans; + } +}; +``` diff --git a/2018.12.26-leetcode53/TheRocket.md b/2018.12.26-leetcode53/TheRocket.md new file mode 100644 index 000000000..975922d1b --- /dev/null +++ b/2018.12.26-leetcode53/TheRocket.md @@ -0,0 +1,13 @@ +```java +class Solution { + public int maxSubArray(int[] nums) { + int maxSum = nums[0]; + int curSum = nums[0]; + for (int i = 1; i < nums.length; ++i) { + curSum = curSum > 0 ? curSum + nums[i] : nums[i]; + maxSum = Math.max(maxSum, curSum); + } + return maxSum; + } +} +``` diff --git a/2018.12.26-leetcode53/Tony the Cyclist.md b/2018.12.26-leetcode53/Tony the Cyclist.md new file mode 100644 index 000000000..e020f0ff5 --- /dev/null +++ b/2018.12.26-leetcode53/Tony the Cyclist.md @@ -0,0 +1,16 @@ +```java +class Solution { + public int maxSubArray(int[] nums) { + int [] n = new int[nums.length]; + n[0] = nums[0]; + for (int i = 1; i < nums.length; i++){ + nums[i] = (nums[i] + nums[i-1]) < nums[i]? nums[i]: (nums[i] + nums[i-1]); + } + int max = nums[0]; + for (int i = 1; i < nums.length; i++){ + max = nums[i] > max? nums[i]: max; + } + return max; + } +} +``` diff --git a/2018.12.26-leetcode53/WYJ.md b/2018.12.26-leetcode53/WYJ.md new file mode 100644 index 000000000..041915ea7 --- /dev/null +++ b/2018.12.26-leetcode53/WYJ.md @@ -0,0 +1,38 @@ +```java +class Solution { + public int maxSubArray(int[] nums) { + return findMaxSub(nums, 0, nums.length - 1); + } + public int findMaxSub(int[] nums, int begin, int end){ + if(begin == end){ + return nums[begin]; + } + else{ + int mid = (begin + end) / 2; + int leftSum = findMaxSub(nums, begin, mid); + int rightSum = findMaxSub(nums, mid + 1, end); + int crossSum = findMaxCrossing(nums, begin, mid, end); + return Math.max(Math.max(leftSum, rightSum), crossSum); + } + } + public int findMaxCrossing(int[] nums, int begin, int mid, int end){ + int leftSum = Integer.MIN_VALUE; + int sum = 0; + for(int i = mid; i >= begin; i--){ + sum += nums[i]; + if(sum > leftSum){ + leftSum = sum; + } + } + int rightSum = Integer.MIN_VALUE; + sum = 0; + for(int i = mid + 1; i <= end; i++){ + sum += nums[i]; + if(sum > rightSum){ + rightSum = sum; + } + } + return leftSum + rightSum; + } +} +``` diff --git a/2018.12.26-leetcode53/marguerite.md b/2018.12.26-leetcode53/marguerite.md new file mode 100644 index 000000000..24009e1b3 --- /dev/null +++ b/2018.12.26-leetcode53/marguerite.md @@ -0,0 +1,24 @@ +###求和,然后判断和是否小于0, + +###因为只要前面的和小于0,那么后面的数加上前面的和就一定比自身小,所以又重新求和, + +###并和之前的最大子序和比较,取最大值。 + + +``` + +class Solution { +public: + int maxSubArray(vector& nums) { + int ans = 0, maxn = INT_MIN; + int len = nums.size(); + for(int i = 0; i < len; i++){ + if(ans < 0) ans = 0; //如果前面的和小0,那么重新开始求和 + ans += nums[i]; + maxn = max(maxn, ans); + } + return maxn; + } + + +``` diff --git a/2018.12.26-leetcode53/sourcema.md b/2018.12.26-leetcode53/sourcema.md new file mode 100644 index 000000000..c98ad1f38 --- /dev/null +++ b/2018.12.26-leetcode53/sourcema.md @@ -0,0 +1,15 @@ +# LeetCode 53 + class Solution { + public int maxSubArray(int[] nums) {//简单的dp思想,如果累加和<0,保存最大值,重新进行累加 + if (nums == null || nums.length == 0) { + return 0; + } + int sum=0,max=Integer.MIN_VALUE; + for (int i = 0; i < nums.length; i++) { + sum += nums[i]; + max = Math.max(sum, max); + sum=sum<0?0:sum; + } + return max; + } +} diff --git "a/2018.12.26-leetcode53/\345\210\230\346\266\246\346\263\275(capture).md" "b/2018.12.26-leetcode53/\345\210\230\346\266\246\346\263\275(capture).md" new file mode 100644 index 000000000..56d16a39a --- /dev/null +++ "b/2018.12.26-leetcode53/\345\210\230\346\266\246\346\263\275(capture).md" @@ -0,0 +1,24 @@ +```java + /** + * 时间复杂度为O(n) + **/ + public static int maxSubArray(int[] nums) { + + int maxSubArray=nums[0]; + int tempSubArray=nums[0]; + + for (int i=1;imaxSubArray)maxSubArray=tempSubArray; + if (i==nums.length-1) return maxSubArray; + + } + + return maxSubArray; + } +``` diff --git "a/2018.12.26-leetcode53/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" "b/2018.12.26-leetcode53/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" new file mode 100644 index 000000000..6c36abac1 --- /dev/null +++ "b/2018.12.26-leetcode53/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" @@ -0,0 +1,15 @@ +class Solution { + public int maxSubArray(int[] nums) { + int res = Integer.MIN_VALUE; + int max = 0; + for(int i = 0; i < nums.length; i++){ + if(max > 0) { + max += nums[i]; + }else{ + max = nums[i]; + } + if(res < max) res = max; + } + return res; + } +} diff --git "a/2018.12.26-leetcode53/\345\246\256\345\217\257.md" "b/2018.12.26-leetcode53/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..4f06e386d --- /dev/null +++ "b/2018.12.26-leetcode53/\345\246\256\345\217\257.md" @@ -0,0 +1,42 @@ +``` +package sy181230; + +/** + * @author suyuan + 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 + +示例: + +输入: [-2,1,-3,4,-1,2,1,-5,4], +输出: 6 +解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 +进阶: + +如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 + */ +public class leetcode_53最大子序和 +{ + + public static void main(String[] args) + { + int[] nums=new int[]{-2,1,-3,4,-1,2,1,-5,4}; + System.out.println(maxSubArray(nums)); + + } + + public static int maxSubArray(int[] nums) + { + if(nums==null ) + return 0; + int sum=nums[0]; + int max=nums[0]; + for(int i=1;i 给定整数数组 nums ,找到一个有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 + +**例子** +> Input: [-2,1,-3,4,-1,2,1,-5,4], +Output: 6 +Explanation: [4,-1,2,1] has the largest sum = 6. + +**思想** +贪心。记录到当前位置的和,只要和大于0,则继续和后面相加;否则summ置0。 + +**解法** +```python +class Solution(object): + def maxSubArray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + res = summ = nums[0] + for num in nums[1:]: + if summ < 0: + summ = 0 + summ += num + res = max(res, summ) + return res +``` \ No newline at end of file diff --git "a/2018.12.26-leetcode53/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.26-leetcode53/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..2ce040968 --- /dev/null +++ "b/2018.12.26-leetcode53/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,26 @@ +``` +class Solution { + public int maxSubArray(int[] nums) { + if(nums.length==1) return nums[0]; + + /* + int localMax = nums[0]; + int globalMax = nums[0]; + for(int i=1;iglobalMax) globalMax = temp; + if(temp<0) temp = 0; + } + + + return globalMax; + } +} +``` diff --git "a/2018.12.27-leetcode121/121. \344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272.md" "b/2018.12.27-leetcode121/121. \344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272.md" new file mode 100644 index 000000000..92ca4c230 --- /dev/null +++ "b/2018.12.27-leetcode121/121. \344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272.md" @@ -0,0 +1,19 @@ +``` +给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 + +如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 + +注意你不能在买入股票前卖出股票。 + +示例 1: + +输入: [7,1,5,3,6,4] +输出: 5 +解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 + 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 +示例 2: + +输入: [7,6,4,3,1] +输出: 0 +解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 +``` diff --git a/2018.12.27-leetcode121/Be a fresh man.md b/2018.12.27-leetcode121/Be a fresh man.md new file mode 100644 index 000000000..ea775d8dc --- /dev/null +++ b/2018.12.27-leetcode121/Be a fresh man.md @@ -0,0 +1,76 @@ +## 121_(买卖股票的最佳时机)Best Time to Buy and Sell Stock +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
+如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
+注意你不能在买入股票前卖出股票。 +### 1.2 输入与输出 +输入: +* vector& prices:长度可变的价格数组prices + +输出: +* int:所能获取的最大利润 +### 1.3 样例 +#### 1.3.1 样例1 +输入: [7,1,5,3,6,4]
+输出: 5
+解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 + 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 +#### 1.3.2 样例2 +输入: [7,6,4,3,1] +输出: 0 +解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 +## 2 思路描述与代码 +### 2.1 思路描述(动态规划法) +dp[i] 表示为第 i + 1 天可获得的最大利润; +此时最大利润可能是下述两种情况: +1. 当前卖出的的情况是prices[i]-最低价 +2. 不是当天卖出的情况是dp[i-1] +于是dp[i] = max(prices[i]-最低价, dp[i-1]);
+dp中只与前一个元素有关,可以写成简化空间复杂度的写法:max_profit = max(prices[i]-最低价, max_profit)。 + +比如输入: [7,1,5,3,6,4];
+i = 0, min_price = 7, dp[0] = 0;
+i = 1, min_price = 1, dp[1] = min(0, 0) = 0;
+i = 2, min_price = 1, dp[2] = min(5 - 1, 0) = 4;
+i = 3, min_price = 1, dp[3] = min(3 - 1, 4) = 4;
+i = 4, min_price = 1, dp[4] = min(6 - 1, 4) = 5;
+i = 5, min_price = 1, dp[5] = min(4 - 1, 5) = 5;
+### 2.2 代码 +```cpp +//函数中涉及到的c++知识 +//vector 是个长度可变的 int 数组,c++里面称为容器 +int maxProfit(vector& prices) { + int len = prices.size(); + //边界情况 + if(len == 0) return 0; + + //当前最大的利益 = max(前一天可能的最大利益, 今天的价钱-最低价) + int max_profit = -2147483648; + int min_price = 2147483647; + for( int i = 0; i < prices.size(); i++ ){ + min_price = min(min_price, prices[i]); + max_profit = max(max_profit, prices[i] - min_price); + } + return max_profit; +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题通过分析在第 x 天可能卖出的最大收益的情况可以很快推出动态规划的递推表达式,然后再做空间的简化即可。 +#### 3.1.1 其他方法 +#### 3.1.1.1 差分+最大连续子列和 +1. 先求差分数组 +2. 求差分数组中的最大连续子列和 + +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +动态规划法|O(1)|O(n) +差分+最大连续子列和|O(n)|O(n) +#### 3.1.3 难点分析 +1. 求递归表达式 +2. 简化空间复杂度 + +### 3.2 拓展 +1. [买卖股票的最佳时机 II](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/)。 diff --git a/2018.12.27-leetcode121/Ostrichcrab.md b/2018.12.27-leetcode121/Ostrichcrab.md new file mode 100644 index 000000000..9f3d933a8 --- /dev/null +++ b/2018.12.27-leetcode121/Ostrichcrab.md @@ -0,0 +1,16 @@ +``` +class Solution { +public: + int maxProfit(vector& prices) { + int ans = 0; + int size = prices.size(); + if(size==0) return 0; + int minn = prices[0]; + for(int i = 1; i < size; i++){ + ans = ans > prices[i]-minn ? ans : prices[i]-minn; + minn = minn > prices[i] ? prices[i] : minn; + } + return ans; + } +}; +``` diff --git a/2018.12.27-leetcode121/TheRocket.md b/2018.12.27-leetcode121/TheRocket.md new file mode 100644 index 000000000..e9c2fdcfe --- /dev/null +++ b/2018.12.27-leetcode121/TheRocket.md @@ -0,0 +1,16 @@ +```java +class Solution { + public int maxProfit(int[] prices) { + if (prices == null || prices.length <= 1) { + return 0; + } + int res = 0; + int minPrice = prices[0]; + for (int price : prices) { + minPrice = Math.min(minPrice, price); + res = Math.max(res, price - minPrice); + } + return res; + } +} +``` diff --git a/2018.12.27-leetcode121/Tony the Cyclist.md b/2018.12.27-leetcode121/Tony the Cyclist.md new file mode 100644 index 000000000..5889e45d6 --- /dev/null +++ b/2018.12.27-leetcode121/Tony the Cyclist.md @@ -0,0 +1,15 @@ +```java +class Solution { + public int maxProfit(int[] prices) { + int maxn = 0; + int minn = 100000; + int dest = 0; + for(int i = 0; i < prices.length; i++){ + minn = minn < prices[i]? minn: prices[i]; + maxn = prices[i]; + dest = maxn-minn > dest? maxn-minn: dest; + } + return dest; + } +} +``` diff --git a/2018.12.27-leetcode121/WYJ.md b/2018.12.27-leetcode121/WYJ.md new file mode 100644 index 000000000..e82da9e27 --- /dev/null +++ b/2018.12.27-leetcode121/WYJ.md @@ -0,0 +1,45 @@ +```java +class Solution { + public int maxProfit(int[] prices) { + if(prices.length <= 1){ + return 0; + } + for(int i = prices.length - 1; i > 0; i--){ + prices[i] = prices[i] - prices[i - 1]; + } + prices[0] = 0; + return maxSubProfit(prices, 0, prices.length - 1); + } + public int maxSubProfit(int[] prices, int begin, int end){ + if(begin == end){ + return prices[begin]; + } + else{ + int mid = (begin + end) / 2; + int leftSum = maxSubProfit(prices, begin, mid); + int rightSum = maxSubProfit(prices, mid + 1, end); + int crossSum = maxCrossProfit(prices, begin, mid, end); + return Math.max(Math.max(leftSum, rightSum), crossSum); + } + } + public int maxCrossProfit(int[] prices, int begin, int mid, int end){ + int leftSum = Integer.MIN_VALUE; + int sum = 0; + for(int i = mid; i >= begin; i--){ + sum += prices[i]; + if(sum > leftSum){ + leftSum = sum; + } + } + int rightSum = Integer.MIN_VALUE; + sum = 0; + for(int i = mid + 1; i <= end; i++){ + sum += prices[i]; + if(sum > rightSum){ + rightSum = sum; + } + } + return leftSum + rightSum; + } +} +``` diff --git a/2018.12.27-leetcode121/marguerite.md b/2018.12.27-leetcode121/marguerite.md new file mode 100644 index 000000000..ec3fa672a --- /dev/null +++ b/2018.12.27-leetcode121/marguerite.md @@ -0,0 +1,27 @@ + +###遇到临时最小的,就保存(1),计算后面比它大的差, + +###保留最大(6-1),遇到后面如果有更小的(0),就保存(0),重复上面工作即可。 + +``` + + +public int maxProfit2(int[] prices) { + if(prices==null||prices.length<=1){ + return 0; + } + int res=0,temp,inv; + temp=prices[0]; + for(int i=1;iinv){ + temp=inv; + }else{ + inv=inv-temp; + res=res>inv?res:inv; + } + } + return res; + + +``` diff --git a/2018.12.27-leetcode121/sourcema.md b/2018.12.27-leetcode121/sourcema.md new file mode 100644 index 000000000..de418a3cf --- /dev/null +++ b/2018.12.27-leetcode121/sourcema.md @@ -0,0 +1,23 @@ +# LeetCode 121 + class Solution { + public int maxProfit(int[] stocks) {//找数组中前后差值最大的结果 + if (stocks.length == 0 || stocks == null) { + return 0; + } + int[] mins = new int[stocks.length]; + int[] maxs = new int[stocks.length]; + mins[0] = stocks[0]; + maxs[stocks.length-1] = stocks[stocks.length-1]; + int res=Integer.MIN_VALUE; + for (int i = 1; i < stocks.length; i++) { + mins[i] = Math.min(mins[i - 1], stocks[i]); + } + for (int i =stocks.length-2 ; i >=0; i--) { + maxs[i] = Math.max(maxs[i + 1], stocks[i]); + } + for (int i = 0; i < stocks.length; i++) { + res = Math.max(res, maxs[i] - mins[i]); + } + return res; + } +} diff --git "a/2018.12.27-leetcode121/\345\210\230\346\266\246\346\263\275(capture).md" "b/2018.12.27-leetcode121/\345\210\230\346\266\246\346\263\275(capture).md" new file mode 100644 index 000000000..b5cdc07c7 --- /dev/null +++ "b/2018.12.27-leetcode121/\345\210\230\346\266\246\346\263\275(capture).md" @@ -0,0 +1,18 @@ +```java + public int maxProfit(int[] prices) { + + int maxProfit=0; + int tempProfit=0; + + for (int i=1;i0){ + tempProfit=tempProfit+(prices[i]-prices[i-1]); + if(tempProfit>maxProfit) maxProfit=tempProfit; + }else{ + tempProfit=0;} + } + + return maxProfit; + } + +``` diff --git "a/2018.12.27-leetcode121/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" "b/2018.12.27-leetcode121/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" new file mode 100644 index 000000000..e3f7b984c --- /dev/null +++ "b/2018.12.27-leetcode121/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" @@ -0,0 +1,15 @@ +class Solution { + public int maxProfit(int[] prices) { + int res = 0; + int max = 0; + for(int i = 1; i < prices.length; i++){ + if(max > 0){ + max += prices[i] - prices[i-1]; + } else { + max = prices[i] - prices[i-1]; + } + if(res < max) res = max; + } + return res; + } +} diff --git "a/2018.12.27-leetcode121/\345\246\256\345\217\257.md" "b/2018.12.27-leetcode121/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..3d81de683 --- /dev/null +++ "b/2018.12.27-leetcode121/\345\246\256\345\217\257.md" @@ -0,0 +1,78 @@ +``` +package sy181230; + +/** + * @author suyuan + 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 + +如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 + +注意你不能在买入股票前卖出股票。 + +示例 1: + +输入: [7,1,5,3,6,4] +输出: 5 +解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 + 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 +示例 2: + +输入: [7,6,4,3,1] +输出: 0 +解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 + */ +public class leetcode_121买卖股票的最佳时机 +{ + + public static void main(String[] args) + { + int[] prices=new int[]{7,1,5,3,6,4}; + System.out.println(maxProfit2(prices)); + + + } + + //贪心 + public static int maxProfit(int[] prices) + { + //根据题意,我们只需要找出数组中最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。 + if(prices == null || prices.length<2) + return 0; + int min=prices[0]; + int profit=0; + + for(int i=1;i 给定一个数组,第 i 个元素是给定股票第 i 天的价格。 +如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 +注意你不能在买入股票前卖出股票。 + +**例子** +> **Example 1:** +Input: [7,1,5,3,6,4] +Output: 5 +Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. + Not 7-1 = 6, as selling price needs to be larger than buying price. + +> **Example 2:** +Input: [7,6,4,3,1] +Output: 0 +Explanation: In this case, no transaction is done, i.e. max profit = 0. + +**思想** +记录到当前位置为止的最小购买价格buy。 +遍历数组,若price > buy,则记录当前卖出的利润;否则,buy = price。 + +**解法** +```python +class Solution(object): + def maxProfit(self, prices): + """ + :type prices: List[int] + :rtype: int + """ + if not prices: + return 0 + + res = 0 + buy = prices[0] # Record the min-buy up to this time + for price in prices[1:]: + if price > buy: + res = max(res, price - buy) + else: + buy = price + return res +``` \ No newline at end of file diff --git "a/2018.12.28-leetcode69/69. x \347\232\204\345\271\263\346\226\271\346\240\271.md" "b/2018.12.28-leetcode69/69. x \347\232\204\345\271\263\346\226\271\346\240\271.md" new file mode 100644 index 000000000..91be54eee --- /dev/null +++ "b/2018.12.28-leetcode69/69. x \347\232\204\345\271\263\346\226\271\346\240\271.md" @@ -0,0 +1,18 @@ +``` +实现 int sqrt(int x) 函数。 + +计算并返回 x 的平方根,其中 x 是非负整数。 + +由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 + +示例 1: + +输入: 4 +输出: 2 +示例 2: + +输入: 8 +输出: 2 +说明: 8 的平方根是 2.82842..., + 由于返回类型是整数,小数部分将被舍去。 +``` diff --git a/2018.12.28-leetcode69/Be a fresh man.md b/2018.12.28-leetcode69/Be a fresh man.md new file mode 100644 index 000000000..41abe369d --- /dev/null +++ b/2018.12.28-leetcode69/Be a fresh man.md @@ -0,0 +1,67 @@ +## 069_(x的平方根)Sqrt(x) +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +实现 int sqrt(int x) 函数。
+计算并返回 x 的平方根,其中 x 是非负整数。
+由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
+### 1.2 输入与输出 +输入: +* int x:求 x 的平方根 + +输出: +* int: x 的平方根 +### 1.3 样例 +#### 1.3.1 样例1 +输入: 4
+输出: 2
+#### 1.3.2 样例2 +输入: 8
+输出: 2
+解释: 8 的平方根是 2.82842...,
+ 由于返回类型是整数,小数部分将被舍去。
+## 2 思路描述与代码 +### 2.1 思路描述(牛顿迭代方法) +令f(t) = x - t^2
+相当于求 f(t) = 0 时的 t(t >= 0)
+利用牛顿迭代公式可以求得 t_new = (t + x/t) / 2
+迭代直到 abs(t_new * t_new - x) 小于指定的精度,然后返回 (int)t_new
+### 2.2 代码 +```cpp +double pricision = 0.00001; +int mySqrt(int x) { + double y = 1.0 * x; + double sqrt_y = 1; + while( abs(y - sqrt_y * sqrt_y) > pricision ){ + sqrt_y = (sqrt_y + y / sqrt_y) / 2; + } + return (int)sqrt_y; +} +``` +## 3 思考与拓展 +### 3.1 思考 +#### 3.1.1 其他方法 +##### 3.1.1.1 二分法 +取左边界 left 为 0, 右边界 right 为 x / 2
+然后算 mid = (left + right) / 2
+如果 mid * mid < x 则扩大左边界 left 为 mid
+否则 扩大右边界 right 为 mid
+重复上述过程直到 abs(mid * mid - x) 小于指定的精度,然后返回 (int)mid
+ +##### 3.1.1.2 平方数判定法 +1 = 1
+1 + 3 = 2^2
+1 + 3 + 5 = 3^2
+1 + 3 + 5 + 7 = 4^2
+... ...
+1 + 3 + 5 + 7 + ... + 2*n-1 = n^2
+可以看出如果求其平方根就是不断减去递增的奇数直到为0,此时减去奇数的次数就是他的平方根。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +二分法|O(1)|O(logx) +平方数判定法|O(1)|O(x^(1/2)) +牛顿迭代方法|O(1)|一般比上述两种方法好,收敛速度快 +#### 3.1.3 难点分析 +1. 推理牛顿迭代的公式。 +### 3.2 拓展 +如果让你求 x 的立方根呢? diff --git a/2018.12.28-leetcode69/Ostrichcrab.md b/2018.12.28-leetcode69/Ostrichcrab.md new file mode 100644 index 000000000..40fc393b0 --- /dev/null +++ b/2018.12.28-leetcode69/Ostrichcrab.md @@ -0,0 +1,59 @@ +``` +class Solution { +public: + int mySqrt(int x) { + return sqrt(x); + } +}; +-------------------------------------- +class Solution { +public: + int mySqrt(int x) { + double pre = 0; + double cur = x; + while(abs(cur-pre)>0.000001){ + pre = cur; + cur = (pre/2+x/(2*pre)); + } + return int(cur); + } +}; +----------------------------------------- + +class Solution +{ +public: + int mySqrt(int x) + { + //数学大神根据牛顿迭代法来求推导出的神奇方法 + assert(x >= 0); + if (x == 0 || x == 1) + { + return x; + } + float tmp = x; + float xhalf = 0.5f*tmp; + int i = *(int*)&tmp; + + i = 0x5f375a86 - (i >> 1); // 这一步是关键 + + tmp = *(float*)&i; + tmp = tmp*(1.5f - xhalf*tmp*tmp); + tmp = tmp*(1.5f - xhalf*tmp*tmp); + tmp = tmp*(1.5f - xhalf*tmp*tmp); + + int ret = 1 / tmp; + if (ret*ret > x) + { + return ret - 1; + } + return ret; + } +}; +---------------------------------------------------- +int x = []() { + std::ios::sync_with_stdio(false); + std::cin.tie(nullptr); + return 0; +}(); +``` diff --git a/2018.12.28-leetcode69/TheRocket.md b/2018.12.28-leetcode69/TheRocket.md new file mode 100644 index 000000000..041788aed --- /dev/null +++ b/2018.12.28-leetcode69/TheRocket.md @@ -0,0 +1,11 @@ +```java +class Solution { + public int mySqrt(int x) { + long r = x; + while (r * r > x) { + r = (r + x / r) / 2; + } + return (int) r; + } +} +``` diff --git a/2018.12.28-leetcode69/Tony the Cyclist.md b/2018.12.28-leetcode69/Tony the Cyclist.md new file mode 100644 index 000000000..a021014ca --- /dev/null +++ b/2018.12.28-leetcode69/Tony the Cyclist.md @@ -0,0 +1,27 @@ +```java +class Solution { + public int mySqrt(int x) { + if (x == 0) { + return 0; + } + if (x == 1) { + return 1; + } + int low = 0; + int high = x/2 + 1; + while (low <= high){ + int mid = (low + high) / 2; + if (mid < x/mid){ + low = mid + 1; + } + else if (mid> x/mid){ + high=mid-1; + } + else{ + return mid; + } + } + return low-1; + } +} +``` diff --git a/2018.12.28-leetcode69/sourcema.md b/2018.12.28-leetcode69/sourcema.md new file mode 100644 index 000000000..c5dfb909d --- /dev/null +++ b/2018.12.28-leetcode69/sourcema.md @@ -0,0 +1,24 @@ +# LeetCode 69 + class Solution { + public int mySqrt(int n) { + if (n == 0) { + return 0; + } + if (n == 1) { + return 1; + } + int left=0; + int right=n; + while (left<=right) { + int mid=(left+right)/2; + if (mid < n/mid) { + left=mid+1; + } else if (mid> n/mid) { + right=mid-1; + } else { + return mid; + } + } + return left-1; + } +} diff --git "a/2018.12.28-leetcode69/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" "b/2018.12.28-leetcode69/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" new file mode 100644 index 000000000..73ea4070f --- /dev/null +++ "b/2018.12.28-leetcode69/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" @@ -0,0 +1,21 @@ +class Solution { + public int mySqrt(int x) { + if(x == 0) return 0; + int low=1; + int hi=x/2+1; + while(low+1x/mid){ + hi=mid; + } + else if(mid= i) && (x/(i+1))<(i+1)) + { + res=i; + break; + } + } + return res; + } + + public static int mySqrt(int x) + { + int mid; + int left=1; + int right=x; + int res=0; + while(left<=right) + { + mid=(left+right)>>1; + if(mid<=x/mid) + { + left=mid+1; + res=mid; + } + else + { + right=mid-1; + } + } + return res; + } + +} +``` diff --git "a/2018.12.28-leetcode69/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.28-leetcode69/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..49c4b2d96 --- /dev/null +++ "b/2018.12.28-leetcode69/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,42 @@ +#### [69. Sqrt(x)](https://leetcode.com/problems/sqrtx/) +**题目描述** +> 实现 int sqrt(int x) 函数。 +计算并返回 x 的平方根,其中 x 是非负整数。 +由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 + +**例子** +> **Example 1:** +Input: 4 +Output: 2 + +> **Example 2:** +Input: 8 +Output: 2 +Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. + +**思想** +int(x**0.5) +二分,注意循环的条件以及最后return的值。如果只让left = mid的话,会造成死循环。 + +**解法** +```python +class Solution: + def mySqrt(self, x): + """ + :type x: int + :rtype: int + """ + if x < 2: + return x + + left, right = 0, x//2 + while left <= right: + mid = (left + right) >> 1 + if mid * mid == x: + return mid + if mid * mid > x: + right = mid - 1 + else: + left = mid + 1 + return left - 1 +``` \ No newline at end of file diff --git "a/2018.12.29-leetcode744/744. \345\257\273\346\211\276\346\257\224\347\233\256\346\240\207\345\255\227\346\257\215\345\244\247\347\232\204\346\234\200\345\260\217\345\255\227\346\257\215.md" "b/2018.12.29-leetcode744/744. \345\257\273\346\211\276\346\257\224\347\233\256\346\240\207\345\255\227\346\257\215\345\244\247\347\232\204\346\234\200\345\260\217\345\255\227\346\257\215.md" new file mode 100644 index 000000000..8cc695310 --- /dev/null +++ "b/2018.12.29-leetcode744/744. \345\257\273\346\211\276\346\257\224\347\233\256\346\240\207\345\255\227\346\257\215\345\244\247\347\232\204\346\234\200\345\260\217\345\255\227\346\257\215.md" @@ -0,0 +1,42 @@ +``` +给定一个只包含小写字母的有序数组letters 和一个目标字母 target,寻找有序数组里面比目标字母大的最小字母。 + +数组里字母的顺序是循环的。举个例子,如果目标字母target = 'z' 并且有序数组为 letters = ['a', 'b'],则答案返回 'a'。 + +示例: + +输入: +letters = ["c", "f", "j"] +target = "a" +输出: "c" + +输入: +letters = ["c", "f", "j"] +target = "c" +输出: "f" + +输入: +letters = ["c", "f", "j"] +target = "d" +输出: "f" + +输入: +letters = ["c", "f", "j"] +target = "g" +输出: "j" + +输入: +letters = ["c", "f", "j"] +target = "j" +输出: "c" + +输入: +letters = ["c", "f", "j"] +target = "k" +输出: "c" +注: + +letters长度范围在[2, 10000]区间内。 +letters 仅由小写字母组成,最少包含两个不同的字母。 +目标字母target 是一个小写字母。 +``` diff --git a/2018.12.29-leetcode744/Be a fresh man.md b/2018.12.29-leetcode744/Be a fresh man.md new file mode 100644 index 000000000..fa11f9c13 --- /dev/null +++ b/2018.12.29-leetcode744/Be a fresh man.md @@ -0,0 +1,99 @@ +## 744_(寻找比目标字母大的最小字母)Find Smallet Letter Greater Than Target +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定一个只包含小写字母的有序数组letters 和一个目标字母 target,寻找有序数组里面比目标字母大的最小字母。 +数组里字母的顺序是循环的。
+举个例子,如果目标字母target = 'z' 并且有序数组为 letters = ['a', 'b'],则答案返回 'a'。 + +__注__: +1. letters长度范围在[2, 10000]区间内。 +2. letters 仅由小写字母组成,最少包含两个不同的字母。 +3. 目标字母target 是一个小写字母。 +### 1.2 输入与输出 +输入: +* vector<_char_>& letters:只包含小写字母的有序数组letters +* char target:目标字母 + +输出: +* char:有序数组里面比目标字母大的最小字母 +### 1.3 样例 +#### 1.3.1 样例1 +输入:
+letters = ["c", "f", "j"]
+target = "a"
+输出: "c" +#### 1.3.2 样例2 +输入: +letters = ["c", "f", "j"]
+target = "c"
+输出: "f"
+#### 1.3.3 样例3 +输入:
+letters = ["c", "f", "j"]
+target = "d"
+输出: "f" +#### 1.3.4 样例4 +输入:
+letters = ["c", "f", "j"]
+target = "g"
+输出: "j" +#### 1.3.5 样例5 +输入:
+letters = ["c", "f", "j"]
+target = "j"
+输出: "c" +#### 1.3.6 样例6 +输入:
+letters = ["c", "f", "j"]
+target = "k"
+输出: "c" + +## 2 思路描述与代码 +### 2.1 思路描述(两遍扫描法) +1. 第一遍扫描记录出现的字符 +2. 第二遍从目标字符的下一个字符开始环形扫描出现的第一个字母 + +比如输入:letters = ["c", "f", "j"],target = "j"
+第一遍扫描后有:dict["c"]=1, dict["f"]=1, dict["j"]=1, 其余字符的dict都是0; +第二遍扫描从 "h" 开始环形扫描,扫到 "c" 时发现其出现过,于是返回 "c" 。 +### 2.2 代码 +```cpp +//函数中涉及到的c++知识 +//vector 是个长度可变的 char 数组,c++里面称为容器 +//vector 是个长度可变的 int 数组,c++里面称为容器 +//vector dict(26, 0) 初始化包含26个元素的可变数组为0 +char nextGreatestLetter(vector& letters, char target) { + //字符初始化为未出现 + vector dict(26, 0); + //一遍扫描记录出现的字符 + int cnt_valid_letter = 0; + int len = letters.size(); + for( int i = 0; i < len; i++ ){ + if(cnt_valid_letter == 26) continue; + if(dict[letters[i] - 'a'] == 0){ + dict[letters[i] - 'a'] = 1; + cnt_valid_letter++; + } + } + //环形扫描比目标字母大的最小字母 + int start = (target - 'a' + 1) % 26; + for( int i = 0; i < 26; i++ ){ + if(dict[(i+start)%26]) return ((i+start)%26+'a'); + } + return -1; +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题利用求模操作实现环形扫描,再配合常见的两遍扫描法即可解决该问题。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +两遍扫描法|O(1)|O(n) +#### 3.1.3 难点分析 +1. 实现环形扫描 + +### 3.2 拓展 +如果给你的数据是链表或者数组数据呢? diff --git a/2018.12.29-leetcode744/Ostrichcrab.md b/2018.12.29-leetcode744/Ostrichcrab.md new file mode 100644 index 000000000..38f4f1ad6 --- /dev/null +++ b/2018.12.29-leetcode744/Ostrichcrab.md @@ -0,0 +1,15 @@ +``` +int x = []() { + std::ios::sync_with_stdio(false); + std::cin.tie(nullptr); + return 0; +}(); +class Solution { +public: + char nextGreatestLetter(vector& letters, char target) { + int index = upper_bound(letters.begin(),letters.end(),target)-letters.begin(); + if(index == letters.size()) index = 0; + return letters[index]; + } +}; +``` diff --git a/2018.12.29-leetcode744/TheRocket.md b/2018.12.29-leetcode744/TheRocket.md new file mode 100644 index 000000000..365f3d8a2 --- /dev/null +++ b/2018.12.29-leetcode744/TheRocket.md @@ -0,0 +1,17 @@ +```java +class Solution { + public char nextGreatestLetter(char[] letters, char target) { + int lo = 0; + int hi = letters.length; + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (target >= letters[mid]) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo == letters.length ? letters[0] : letters[lo]; + } +} +``` diff --git a/2018.12.29-leetcode744/Tony the Cyclist.md b/2018.12.29-leetcode744/Tony the Cyclist.md new file mode 100644 index 000000000..6cc343526 --- /dev/null +++ b/2018.12.29-leetcode744/Tony the Cyclist.md @@ -0,0 +1,13 @@ +```python +class Solution(object): + def nextGreatestLetter(self, letters, target): + """ + :type letters: List[str] + :type target: str + :rtype: str + """ + for x in letters: + if x >target: + return x + return letters[0] +``` diff --git a/2018.12.29-leetcode744/WYJ.md b/2018.12.29-leetcode744/WYJ.md new file mode 100644 index 000000000..1f070e235 --- /dev/null +++ b/2018.12.29-leetcode744/WYJ.md @@ -0,0 +1,20 @@ +```java +class Solution { + public char nextGreatestLetter(char[] letters, char target) { + + int distance = Integer.MAX_VALUE; + int index = -1; + for(int i = 0; i < letters.length; i++){ + int tempDis = (int)(letters[i] - target); + if(tempDis < 0){ + tempDis += 26; + } + if(tempDis > 0&&tempDis < distance){ + distance = tempDis; + index = i; + } + } + return letters[index]; + } +} +``` diff --git a/2018.12.29-leetcode744/YYT.md b/2018.12.29-leetcode744/YYT.md new file mode 100644 index 000000000..42d9bcac2 --- /dev/null +++ b/2018.12.29-leetcode744/YYT.md @@ -0,0 +1,40 @@ + /** + * 二分法 + * 因为比较太多运行时间也没有更短 + */ + public char nextGreatestLetter1(char[] letters, char target) { + int length = letters.length; + if (letters[0] - target < 0 && letters[length - 1] - target < 0){ + return letters[0]; + } + int start = 0; + int end = length - 1; + int binary = 0; + int distance = Integer.MAX_VALUE; + char res = ' '; + while (start <= end) { + binary = (start + end) / 2; + if (letters[binary] - target > 0){ + if (letters[binary] - target < distance){ + res = letters[binary]; + distance = letters[binary] - target; + } + if(end - start == 0){ + return res; + } + end = binary - 1; + }else { + start = binary + 1; + } + } + return res; + } + + public char nextGreatestLetter(char[] letters, char target) { + for (int i = 0; i < letters.length; i++) { + if (letters[i] - target > 0){ + return letters[i]; + } + } + return letters[0]; + } diff --git a/2018.12.29-leetcode744/sourcema.md b/2018.12.29-leetcode744/sourcema.md new file mode 100644 index 000000000..5cd553602 --- /dev/null +++ b/2018.12.29-leetcode744/sourcema.md @@ -0,0 +1,17 @@ +# LeetCode 744 + class Solution { + public char nextGreatestLetter(char[] letters, char target) {//简单的二分思路 + //test + int left=0; + int right=letters.length-1; + while(left<=right){ + int mid=(left+right)>>1; + if(letters[mid]>target){ + right=mid-1; + }else { + left=mid+1; + } + } + return letters[left%letters.length]; + } +} diff --git "a/2018.12.29-leetcode744/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" "b/2018.12.29-leetcode744/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" new file mode 100644 index 000000000..90ae2a5fb --- /dev/null +++ "b/2018.12.29-leetcode744/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" @@ -0,0 +1,8 @@ +class Solution { + public char nextGreatestLetter(char[] letters, char target) { + int i = 0; + while(i < letters.length && letters[i++] <= target); + if(i == letters.length && letters[i-1] <= target) return letters[0]; + return letters[i-1]; + } +} diff --git "a/2018.12.29-leetcode744/\345\246\256\345\217\257.md" "b/2018.12.29-leetcode744/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..804e38bd0 --- /dev/null +++ "b/2018.12.29-leetcode744/\345\246\256\345\217\257.md" @@ -0,0 +1,83 @@ +``` +package sy190101; + +/** + * @author suyuan + * + 给定一个只包含小写字母的有序数组letters 和一个目标字母 target, + 寻找有序数组里面比目标字母大的最小字母。 + +数组里字母的顺序是循环的。举个例子,如果目标字母target = 'z' 并且有序数组为 letters = ['a', 'b'],则答案返回 'a'。 + +示例: + +输入: +letters = ["c", "f", "j"] +target = "a" +输出: "c" + +输入: +letters = ["c", "f", "j"] +target = "c" +输出: "f" + +输入: +letters = ["c", "f", "j"] +target = "d" +输出: "f" + +输入: +letters = ["c", "f", "j"] +target = "g" +输出: "j" + +输入: +letters = ["c", "f", "j"] +target = "j" +输出: "c" + +输入: +letters = ["c", "f", "j"] +target = "k" +输出: "c" +注: + +letters长度范围在[2, 10000]区间内。 +letters 仅由小写字母组成,最少包含两个不同的字母。 +目标字母target 是一个小写字母。 + */ +public class leetcode_744寻找比目标字母大的最小字母 +{ + + public static void main(String[] args) + { + char[] letters=new char[] {'c', 'f', 'j'}; + System.out.println(nextGreatestLetter(letters, 'c')); + + + } + // 给定一个只包含小写字母的有序数组letters 和一个目标字母 target, + // 寻找有序数组里面比目标字母大的最小字母。 + // 数组里字母的顺序是循环的。 + + //读题:有序数组 比目标字母大的最小字母 字母的顺序是循环的 + //二分 + public static char nextGreatestLetter(char[] letters, char target) + { + int mid; + int left=0; + int right=letters.length-1; + while(left<=right) + { + mid=(left+right)>>1; + if(letters[mid]<=target) + left=mid+1; + else + right=mid-1; + + } + return left 给定一只包含小写字母的有序数组letters 和一个目标字母 target,寻找有序数组里面比目标字母大的最小字母。 + +> 数组里字母的顺序是循环的。举个例子,如果目标字母target = 'z' 并且有序数组为 letters = ['a', 'b'],则答案返回 'a'。 + +**例子** +> Input:letters = ["c", "f", "j"] target = "a" +Output: "c" + +> Input:letters = ["c", "f", "j"] target = "c" +Output: "f" + +**思想** +给定的是有序列表,所以考虑二分:找到第一个比target大的元素。 +若未找到,说明列表元素都比target小。此时考虑wrap around,返回第一个元素即可。 + +**解法** +```python +class Solution(object): + def nextGreatestLetter(self, letters, target): + """ + :type letters: List[str] + :type target: str + :rtype: str + """ + left, right = 0, len(letters)-1 + while left <= right: + mid = (left + right) >> 1 + if letters[mid] <= target: + left = mid + 1 + else: + if mid == 0 or letters[mid-1] <= target: + return letters[mid] + right = mid - 1 + return letters[0] +``` \ No newline at end of file diff --git "a/2018.12.29-leetcode744/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.29-leetcode744/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..55244d555 --- /dev/null +++ "b/2018.12.29-leetcode744/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,29 @@ +``` +class Solution { + public char nextGreatestLetter(char[] letters, char target) { + if(letters.length==0||null==letters) return '\0'; + int left = 0; + int right = letters.length-1; + + while(lefttarget){ + right = mid; + } + } + return left==letters.length-1&&letters[left]<=target? letters[0]:letters[left]; + + /* + for(int i = 0;i= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { + builder.append(c); + } else { + String temp = builder.toString(); + world = temp.length() > 0 ? temp : world; + builder.setLength(0); + } + if (i == (s.length() - 1)) { + String temp = builder.toString(); + world = temp.length() > 0 ? temp : world; + builder.setLength(0); + } + } + return world == null ? 0 : world.length(); + } + + public static void main(String[] args) { + System.out.println( new Solution_58().lengthOfLastWord("Hello World")); + + } +} diff --git a/2018.12.3-leetcode58/Avalon.md b/2018.12.3-leetcode58/Avalon.md new file mode 100644 index 000000000..84465d2c5 --- /dev/null +++ b/2018.12.3-leetcode58/Avalon.md @@ -0,0 +1,8 @@ +class Solution { + public int lengthOfLastWord(String s) { + String[] sArr = s.trim().split(" "); + if (sArr.length == 0) + return 0; + return sArr[sArr.length-1].length(); + } +} diff --git a/2018.12.3-leetcode58/Be a fresh man.md b/2018.12.3-leetcode58/Be a fresh man.md new file mode 100644 index 000000000..a20da181e --- /dev/null +++ b/2018.12.3-leetcode58/Be a fresh man.md @@ -0,0 +1,77 @@ +## 058_(最后一个单词的长度)Length of Last Word +## 1 问题描述、输入输出与样例 +### 1.1 问题描述 +给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
+如果不存在最后一个单词,请返回 0 。 + +__说明__:一个单词是指由字母组成,但不包含任何空格的字符串。 + +### 1.2 输入与输出 +输入:
+* string s:仅包含大小写字母和空格 ' ' 的字符串 s
+输出:
+* int:最后一个单词的长度 + +### 1.3 样例 +#### 1.3.1 样例1 +输入: "Hello World"
+输出: 5 + +#### 1.3.2 样例2 +输入: "Hello "
+输出: 5 + +## 2 思路描述与代码 +### 2.1 思路描述(单词计数法) +cnt_last_word 为对单词的计数值 +```cpp +cnt_last_word = 0; +i = 0; +while( i < len(s) ){ + if(s[i] == ' '){ + Skip consecutive 0; + //case like 1.3.2 + if(s[i] is the last charater of s) return cnt_last_word; + else clear cnt_last_word; + } + else ++cnt_last_word +} +//case like 1.3.1 +return cnt_last_word; +``` +### 2.2 代码 +```cpp +int lengthOfLastWord(string s) { + int s_len = s.size(); + int cnt_last_word = 0; + int i = 0; + while( i < s_len ){ + if(s[i] == ' ') { + //跳过重复的 ' ' + while( i + 1 < s_len && s[i + 1] == ' ') i++; + //如果最后一个也是 ' ',返回连续的 '' 前的单词的长度 + if(i == s_len - 1) return cnt_last_word; + else cnt_last_word = 0; + } + //否则加1 + else ++cnt_last_word; + ++i; + } + return cnt_last_word; +} +``` + +## 3 思考与拓展 +### 3.1 思考 +本题较为简单,在增加 1.3.2 样例2 的特殊处理后即可。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +单词计数法|O(1)|O(n) +#### 3.1.3 难点分析 +1. 跳跃重复的' ' +2. 需要考虑字符串 s 的尾巴是以一段连续的 ' ' 结尾 +### 3.2 拓展 +如果给你的数据是链表或者数组数据呢? diff --git a/2018.12.3-leetcode58/FFFro.md b/2018.12.3-leetcode58/FFFro.md new file mode 100644 index 000000000..00e1bc8c9 --- /dev/null +++ b/2018.12.3-leetcode58/FFFro.md @@ -0,0 +1,8 @@ +class Solution { + public int lengthOfLastWord(String s) { + String[] s1 = s.split(" "); + if (s1.length == 0) + return 0; + return s1[s1.length-1].length(); + } +} diff --git a/2018.12.3-leetcode58/Felix.md b/2018.12.3-leetcode58/Felix.md new file mode 100644 index 000000000..d86892a0a --- /dev/null +++ b/2018.12.3-leetcode58/Felix.md @@ -0,0 +1,22 @@ +```javascript +package leetcode.easy; +/** + * @author Felix + * @date 2018年11月17日下午10:52:33 + @version 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 +如果不存在最后一个单词,请返回 0 。 +说明:一个单词是指由字母组成,但不包含任何空格的字符串。 +示例:输入: "Hello World" 输出: 5 + */ +public class LengthOfLastWord { + public int lengthOfLastWord(String s) { + if(s == null || s.trim().length() == 0) + return 0; + String[] str = s.split(" "); + String res = str[str.length-1]; + + return res.length(); + } +} + +``` diff --git a/2018.12.3-leetcode58/GatesMa.md b/2018.12.3-leetcode58/GatesMa.md new file mode 100644 index 000000000..f6e951940 --- /dev/null +++ b/2018.12.3-leetcode58/GatesMa.md @@ -0,0 +1,15 @@ +# c++ +```cpp +class Solution { +public: + int lengthOfLastWord(string s) { + stringstream ss; + ss << s; + string str; + while(ss){ + ss >> str; + } + return str.length(); + } +}; +``` diff --git a/2018.12.3-leetcode58/Istroyforever.md b/2018.12.3-leetcode58/Istroyforever.md new file mode 100644 index 000000000..145707a23 --- /dev/null +++ b/2018.12.3-leetcode58/Istroyforever.md @@ -0,0 +1,18 @@ +//leetcode off 58 +class Solution { +public: + int lengthOfLastWord(string s) { + if(s.size()==0) return 0; + int i=s.size()-1; + while(i>=0 && s[i]==' '){ + i--; + } + int count=0; + while(i>=0 && (s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){ + i--; + count++; + } + return count; + + } +}; diff --git a/2018.12.3-leetcode58/Ostrichcrab.md b/2018.12.3-leetcode58/Ostrichcrab.md new file mode 100644 index 000000000..aeb4cdf97 --- /dev/null +++ b/2018.12.3-leetcode58/Ostrichcrab.md @@ -0,0 +1,21 @@ +``` +class Solution { +public: + int lengthOfLastWord(string s) { + while(s[s.length()-1]==' ') s.pop_back(); + s.insert(s.begin(),' '); + reverse(s.begin(),s.end()); + int len = 0; + for(int i = 0; i < s.length(); i++) + { + while(s[i]!=' ') + { + len++; + i++; + } + break; + } + return len; + } +}; +``` diff --git a/2018.12.3-leetcode58/Sagittarius.md b/2018.12.3-leetcode58/Sagittarius.md new file mode 100644 index 000000000..b869a3c4d --- /dev/null +++ b/2018.12.3-leetcode58/Sagittarius.md @@ -0,0 +1,26 @@ +``` +class Solution { +public: + int lengthOfLastWord(string s) { + int len=s.size(); + char space=' '; + int i=len-1; + while(i>=0) + { + if(s[i]==space) + i--; + else + break; + } + if(i==-1) + return 0; + else + { + len=i; + while(i>=0&&s[i]!=space) + i--; + } + return len-i; + } +}; +``` diff --git a/2018.12.3-leetcode58/Sunny.md b/2018.12.3-leetcode58/Sunny.md new file mode 100644 index 000000000..f2189090c --- /dev/null +++ b/2018.12.3-leetcode58/Sunny.md @@ -0,0 +1,14 @@ +```java +class Solution { + public int lengthOfLastWord(String s) { + if (s == null) return 0; + int i = s.lastIndexOf(" "); + if (i < 0) return s.length(); + if (i == (s.length() - 1) && s.length() > 1) { + s = s.substring(0, i); + return lengthOfLastWord(s); + } + return s.substring(i+1, s.length()).length(); + } +} +``` diff --git a/2018.12.3-leetcode58/TheRocket.md b/2018.12.3-leetcode58/TheRocket.md new file mode 100644 index 000000000..7ff3875ca --- /dev/null +++ b/2018.12.3-leetcode58/TheRocket.md @@ -0,0 +1,13 @@ +```java +class Solution { + public int lengthOfLastWord(String s) { + int res = 0; + int i = s.length() - 1; + for (; i >= 0 && s.charAt(i) == ' '; --i); + for (; i >= 0 && s.charAt(i) != ' '; --i) { + ++res; + } + return res; + } +} +``` diff --git a/2018.12.3-leetcode58/Tony the Cyclist.md b/2018.12.3-leetcode58/Tony the Cyclist.md new file mode 100644 index 000000000..84ee9a1da --- /dev/null +++ b/2018.12.3-leetcode58/Tony the Cyclist.md @@ -0,0 +1,49 @@ +Java +``` +class Solution { + public int lengthOfLastWord(String s) { + String [] ss = s.trim().split(" "); + return ss[ss.length-1].length(); + } +} +``` + +Python +``` +class Solution(object): + def lengthOfLastWord(self, s): + """ + :type s: str + :rtype: int + """ + l = s.strip().split(' ') + return len(l[-1]) +``` +C++ +``` +class Solution { +public: + int lengthOfLastWord(string s) { + int len = (int)s.length(); + int left = 0; + int right = len - 1; + int count = 0; + while (s[left] == ' '){ + left ++; + } + while (s[right] == ' ') { + right --; + } + //string ss = s.substr(left, right+1); + for (int i = left; i < right+1; i++){ + if (s[i] == ' '){ + count = 0; + } + else{ + count ++; + } + } + return count; + } +}; +``` diff --git a/2018.12.3-leetcode58/WhiteNight.md b/2018.12.3-leetcode58/WhiteNight.md new file mode 100644 index 000000000..754218ef3 --- /dev/null +++ b/2018.12.3-leetcode58/WhiteNight.md @@ -0,0 +1,23 @@ +>```java +>/** +> * leetcode58 最后一个单词的长度 +> * +> */ +>public class S5 { +> public int lengthOfLastWord(String s) { +> String[] string = s.split(" "); +> if (string == null || string.length == 0) +> return 0; +> int i = string.length - 1; +> return string[i].length(); +> } +> +> public static void main(String[] args) { +> S5 s = new S5(); +> String string = "Hello World"; +> int res = s.lengthOfLastWord(string); +> System.out.println(res); +> } +>} +>``` + diff --git a/2018.12.3-leetcode58/disappo1nted.md b/2018.12.3-leetcode58/disappo1nted.md new file mode 100644 index 000000000..d3a7aae6e --- /dev/null +++ b/2018.12.3-leetcode58/disappo1nted.md @@ -0,0 +1,10 @@ +class Solution { + public int lengthOfLastWord(String s) { + String[] res=s.split(" "); + if(res.length==0) + return 0; + else + return res[res.length-1].length(); + + } +} diff --git a/2018.12.3-leetcode58/fish.md b/2018.12.3-leetcode58/fish.md new file mode 100644 index 000000000..625f1d1e1 --- /dev/null +++ b/2018.12.3-leetcode58/fish.md @@ -0,0 +1,13 @@ +>给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 +>如果不存在最后一个单词,请返回 0 。 +>说明:一个单词是指由字母组成,但不包含任何空格的字符串。 + +``` +public static int lengthOfLastWord(String str){ + String trim = str.trim(); + if (str.matches("[a-zA-Z ]*") && !trim.isEmpty()) { + int index = trim.lastIndexOf(' '); + return index < 0 ? trim.length() : trim.length() - index - 1; + } + return 0; +} diff --git a/2018.12.3-leetcode58/halfofwater.md b/2018.12.3-leetcode58/halfofwater.md new file mode 100644 index 000000000..4e03ae163 --- /dev/null +++ b/2018.12.3-leetcode58/halfofwater.md @@ -0,0 +1,21 @@ +## LeetCode 58 + +``` C++ +class Solution { +public: + int lengthOfLastWord(string s) { + + stringstream input(s); + string word; + vector vec; + while (input >> word) { + vec.push_back(word); + } + if (vec.size() != 0) + return vec[vec.size() - 1].size(); + else + return 0; + + } +}; +``` diff --git a/2018.12.3-leetcode58/kiritocly.md b/2018.12.3-leetcode58/kiritocly.md new file mode 100644 index 000000000..a8610f327 --- /dev/null +++ b/2018.12.3-leetcode58/kiritocly.md @@ -0,0 +1,7 @@ + private static int solution(String input) { + String[] splits = input.split(" "); + if (splits.length == 0) { + return 0; + } + return splits[splits.length - 1].length(); + } diff --git a/2018.12.3-leetcode58/marguerite.md b/2018.12.3-leetcode58/marguerite.md new file mode 100644 index 000000000..9a9453285 --- /dev/null +++ b/2018.12.3-leetcode58/marguerite.md @@ -0,0 +1,37 @@ +058_(最后一个单词的长度)Length of Last Word +1.1 问题描述 +给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 +如果不存在最后一个单词,请返回 0 。 +说明:一个单词是指由字母组成,但不包含任何空格的字符串。 +1.2 输入与输出 +输入: +string s:仅包含大小写字母和空格 ' ' 的字符串 s +输出: +int:最后一个单词的长度 +1.3 样例 +1.3.1 样例1 +输入: "Hello World" +输出: 5 +1.3.2 样例2 +输入: "Hello " +输出: 5 + +java版: +import java.util.Scanner; +public class Main{ + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + if(in.hasNext()) { + String[]strings words = in.nextLine().split(" "); + System.out.println(words[words.length-1].length()); + }else + System.out.println(0); + } +} + +python版: +class Solution: + def lengthOfLastWord(self, s): + return len(s.strip(' ').split(' ')[-1]) +//这个写法简单,因为字符串有一个方法是分割字符串方法split(),这里只要用空格将字符串分割然后返回 +最后一个字符串的长度即可,另外要注意的是分割之前先用strip()方法将字符串最后的空格删除掉,否则会分割出一个空字符串在最后。 diff --git a/2018.12.3-leetcode58/sourcema.md b/2018.12.3-leetcode58/sourcema.md new file mode 100644 index 000000000..017d7b7c7 --- /dev/null +++ b/2018.12.3-leetcode58/sourcema.md @@ -0,0 +1,18 @@ +# LeetCode 58 + class Solution { + public int lengthOfLastWord(String s) { + if (s == null || s.length() == 0) { + return 0; + } + String str = s.trim(); + int length=0; + for (int i=str.length()-1;i>=0;i--) { + if (str.charAt(i) != ' ') { + length++; + } else { + break; + } + } + return length; + } +} diff --git a/2018.12.3-leetcode58/syuan.md b/2018.12.3-leetcode58/syuan.md new file mode 100644 index 000000000..77dfbd7c4 --- /dev/null +++ b/2018.12.3-leetcode58/syuan.md @@ -0,0 +1,47 @@ +##### 题目 +``` +给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 + +如果不存在最后一个单词,请返回 0 。 + +说明:一个单词是指由字母组成,但不包含任何空格的字符串。 + +示例: + +输入: "Hello World" +输出: 5 +``` +##### 代码 +``` +class Solution { + public int lengthOfLastWord(String s) { + String str=s.trim(); + String[] strArray=s.split(" "); + String lastStr=strArray[strArray.length-1]; + return lastStr.trim().length(); + } +} +``` +> 要删除掉字符串中前后的空格 +##### 代码2 + +``` +class Solution { + public int lengthOfLastWord(String s) { + String str=s.trim(); + if (str==null) { + return 0; + } + int count=0,i=str.length()-1; + while(i>=0){ + if (str.charAt(i)!=' ') { + count++; + i--; + }else{ + break; + } + } + return count; + } +} +``` diff --git a/2018.12.3-leetcode58/tongLuoWan.md b/2018.12.3-leetcode58/tongLuoWan.md new file mode 100644 index 000000000..a1e87a28b --- /dev/null +++ b/2018.12.3-leetcode58/tongLuoWan.md @@ -0,0 +1,9 @@ +``` +public class Solution { + public int lengthOfLastWord(String s) { + String[] tt; + tt = s.split(" "); + return tt.length == 0?0:tt[tt.length-1].length(); + } +} +``` diff --git a/2018.12.3-leetcode58/zjukk.md b/2018.12.3-leetcode58/zjukk.md new file mode 100644 index 000000000..481fb2b25 --- /dev/null +++ b/2018.12.3-leetcode58/zjukk.md @@ -0,0 +1,11 @@ +``` +class Solution { +public: + int lengthOfLastWord(string s) { + istringstream is(s); + string tmp; + while (is >> tmp); + return tmp.size(); + } +}; +``` diff --git "a/2018.12.3-leetcode58/\343\200\202V1ncentzzZ.md" "b/2018.12.3-leetcode58/\343\200\202V1ncentzzZ.md" new file mode 100644 index 000000000..0141d9d20 --- /dev/null +++ "b/2018.12.3-leetcode58/\343\200\202V1ncentzzZ.md" @@ -0,0 +1,27 @@ + +58. 最后一个单词的长度 https://leetcode-cn.com/problems/length-of-last-word/ + +给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 + +如果不存在最后一个单词,请返回 0 。 + +说明:一个单词是指由字母组成,但不包含任何空格的字符串。 + +示例: + +输入: "Hello World" +输出: 5 + + +class Solution { + public int lengthOfLastWord(String s) { + s = s.trim(); + int result = 0; + if("".equals(s)) return result; + if(!s.contains(" ")) return s.length(); + for(int i = s.lastIndexOf(" ")+1; i= 0; i--){ + if (s.charAt(i) == ' '){ + if (result == 0)continue; + break; + } + result++; + } + return result; + } +``` diff --git "a/2018.12.3-leetcode58/\344\272\221\346\267\261\344\270\215\345\217\271.md" "b/2018.12.3-leetcode58/\344\272\221\346\267\261\344\270\215\345\217\271.md" new file mode 100644 index 000000000..bf3f01d8a --- /dev/null +++ "b/2018.12.3-leetcode58/\344\272\221\346\267\261\344\270\215\345\217\271.md" @@ -0,0 +1,9 @@ +``` +public int lengthOfLastWord(String s) { + if(s==null || s.trim().equals("")){ + return 0; + } + String[] arr = s.split(" "); + return arr[arr.length-1].length(); + } +``` diff --git "a/2018.12.3-leetcode58/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.3-leetcode58/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..036d3ba2e --- /dev/null +++ "b/2018.12.3-leetcode58/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,17 @@ +```java +class Solution { + public int lengthOfLastWord(String s) { + if(s==null||s.length()==0)return 0; + int res=0; + int i=s.length()-1; + while(i>=0&&s.charAt(i)==' ')i--; + for(;i>=0;i--){ + if(s.charAt(i)!=' '){ + res++; + } + else break; + } + return res; + } +} +``` diff --git "a/2018.12.3-leetcode58/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" "b/2018.12.3-leetcode58/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" new file mode 100644 index 000000000..9e5b6c5f7 --- /dev/null +++ "b/2018.12.3-leetcode58/\345\244\247\351\255\224\347\216\213\347\210\261\347\251\277\345\255\226\347\203\237\347\255\222.md" @@ -0,0 +1,10 @@ +``` +class Solution { + public int lengthOfLastWord(String s) { + String [] list = s.split(" ");//定义字符串数组,以空格来分割字符串 + if(list.length == 0)//字符串长度是0直接返回 + return 0; + return list[list.length-1].length();//返回最后一个字符串的长度 + } +} +``` diff --git "a/2018.12.3-leetcode58/\345\256\266" "b/2018.12.3-leetcode58/\345\256\266" new file mode 100644 index 000000000..708aa18f0 --- /dev/null +++ "b/2018.12.3-leetcode58/\345\256\266" @@ -0,0 +1,11 @@ +``` +func lengthOfLastWord(s string) int { + l := len(s) + i := l-1 + count := 0 + for ;i>=0 && s[i] == ' ';i--{} + for ;i>=0 && s[i] != ' ';i--{count++} + return count +} + +``` diff --git "a/2018.12.3-leetcode58/\345\274\240\345\260\217\350\203\226.md" "b/2018.12.3-leetcode58/\345\274\240\345\260\217\350\203\226.md" new file mode 100644 index 000000000..262375eb6 --- /dev/null +++ "b/2018.12.3-leetcode58/\345\274\240\345\260\217\350\203\226.md" @@ -0,0 +1,20 @@ + class Solution{ + public: + int lengthOfLastWorld(string s){ + int slength=s.size(); + int i=slength-1,length=0; + if(s.size()==0)return 0; + for(i;i>=0;i--) + { + if(s[i]!=' ') + { + break; + } + } + for(i;s[i]!=' '&&i>=0;i--) + { + length++; + } + return length; + } + }; diff --git "a/2018.12.3-leetcode58/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" "b/2018.12.3-leetcode58/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" new file mode 100644 index 000000000..14389ea51 --- /dev/null +++ "b/2018.12.3-leetcode58/\346\210\221\347\210\261\345\220\203\347\223\234\345\255\220.md" @@ -0,0 +1,14 @@ +#leetcode 58 +``` +class Solution { + public int lengthOfLastWord(String s) { + String[] ss=s.split(" "); + int index=0; + if(ss.length>0){ + index=ss[ss.length-1].length(); + + } + return index; + } +} +``` diff --git "a/2018.12.3-leetcode58/\346\234\200\345\220\216\344\270\200\344\270\252\345\215\225\350\257\215\347\232\204\351\225\277\345\272\246.md" "b/2018.12.3-leetcode58/\346\234\200\345\220\216\344\270\200\344\270\252\345\215\225\350\257\215\347\232\204\351\225\277\345\272\246.md" new file mode 100644 index 000000000..b191f3ef6 --- /dev/null +++ "b/2018.12.3-leetcode58/\346\234\200\345\220\216\344\270\200\344\270\252\345\215\225\350\257\215\347\232\204\351\225\277\345\272\246.md" @@ -0,0 +1,5 @@ +给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 + +如果不存在最后一个单词,请返回 0 。 + +说明:一个单词是指由字母组成,但不包含任何空格的字符串。 diff --git "a/2018.12.3-leetcode58/\346\235\216\347\242\247\346\266\265.md" "b/2018.12.3-leetcode58/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..236ea758a --- /dev/null +++ "b/2018.12.3-leetcode58/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,25 @@ +#### [58. Length of Last Word](https://leetcode.com/problems/length-of-last-word/) +**题目描述** +> 给定一个只包含大小写字母或空字符的字符串s,返回字符串中最后一个单词的长度。如果最后一个单词不存在,返回0。 + +> 单词 - 只包含非空格字符的字符序列。 + +**例子** +> Input: "Hello World" +Output: 5 + +**思想** +比较简单。注意:当s只包含空格时的情况 +**解法** +```python +class Solution(object): + def lengthOfLastWord(self, s): + """ + :type s: str + :rtype: int + """ + s = s.split() + if not s: + return 0 + return len(s[-1]) +``` diff --git "a/2018.12.3-leetcode58/\346\235\250.md" "b/2018.12.3-leetcode58/\346\235\250.md" new file mode 100644 index 000000000..d8a5c0858 --- /dev/null +++ "b/2018.12.3-leetcode58/\346\235\250.md" @@ -0,0 +1,13 @@ +``` +public int firstUniqChar(String s) { + int res = -1; + for(char i ='a';i<='z';i++){ + int index = s.indexOf(i); + if(index!=-1 && index == s.lastIndexOf(i)){ + res = (res==-1 || res > index) ? index : res; + } + } + return res; +} + +``` diff --git "a/2018.12.3-leetcode58/\346\271\233\346\261\237\347\224\262\351\270\237.md" "b/2018.12.3-leetcode58/\346\271\233\346\261\237\347\224\262\351\270\237.md" new file mode 100644 index 000000000..ee65e90cd --- /dev/null +++ "b/2018.12.3-leetcode58/\346\271\233\346\261\237\347\224\262\351\270\237.md" @@ -0,0 +1,9 @@ +``` +public int lengthOfLastWord(String s) { + if (s == null || s.length() == 0){ + return 0; + } + String[] strs = s.split(" "); + int last = strs.length - 1; + return strs[last].length(); +} diff --git "a/2018.12.3-leetcode58/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2018.12.3-leetcode58/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..4f42c9e1e --- /dev/null +++ "b/2018.12.3-leetcode58/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,23 @@ +``` + + +class Solution { +public: + int lengthOfLastWord(string s) { + int end = s.length()-1; + while(s[end] == ' ') + end--; + + int ret = 0; + while(end>=0 && s[end]!=' ') + { + end--; + ret++; + } + + return ret; + } +}; + + +``` diff --git "a/2018.12.3-leetcode58/\350\216\216\350\216\216.md" "b/2018.12.3-leetcode58/\350\216\216\350\216\216.md" new file mode 100644 index 000000000..c40a4a245 --- /dev/null +++ "b/2018.12.3-leetcode58/\350\216\216\350\216\216.md" @@ -0,0 +1,12 @@ +``` +class Solution: + def lengthOfLastWord(self, s): + """ + :type s: str + :rtype: int + """ + list1 = s.strip().split(' ') + last = list1[-1] + return len(last) +``` + diff --git "a/2018.12.3-leetcode58/\351\230\263.md" "b/2018.12.3-leetcode58/\351\230\263.md" new file mode 100644 index 000000000..4b5309339 --- /dev/null +++ "b/2018.12.3-leetcode58/\351\230\263.md" @@ -0,0 +1,18 @@ +class Solution { + public int lengthOfLastWord(String s) { + int len = 0; + //空格串trim掉为空字符串 + s = s.trim(); + if(s == ""){ + len = 0; + }else{ + char[] chs = s.toCharArray(); + int i = chs.length - 1; + while(i >= 0&&chs[i] != ' '){ + i--; + len++; + } + } + return len; + } +} diff --git "a/2018.12.3-leetcode58/\351\235\222\350\241\253\345\277\206\347\254\231.md" "b/2018.12.3-leetcode58/\351\235\222\350\241\253\345\277\206\347\254\231.md" new file mode 100644 index 000000000..23d7ee364 --- /dev/null +++ "b/2018.12.3-leetcode58/\351\235\222\350\241\253\345\277\206\347\254\231.md" @@ -0,0 +1,14 @@ +class LeetCode58 { + + public int lengthOfLastWord(String s) { + if(s==null||s.length()==0) { + return 0; + } + char[] ch=s.toCharArray(); + int i; + for(i=ch.length-1;i>=0&&ch[i]==' ';i--); + int j=i; + for(;j>=0&&ch[j]!=' ';j--); + return i-j; + } +} diff --git "a/2018.12.3-leetcode58/\351\273\216\346\230\216\345\210\235\351\206\222.md" "b/2018.12.3-leetcode58/\351\273\216\346\230\216\345\210\235\351\206\222.md" new file mode 100644 index 000000000..3624a0865 --- /dev/null +++ "b/2018.12.3-leetcode58/\351\273\216\346\230\216\345\210\235\351\206\222.md" @@ -0,0 +1,34 @@ +``` +class Solution { + public int lengthOfLastWord(String s) { + int len = s.length(); + int flag = 0,count=0; + if((len==0)||(s==null)){ + return 0; + } + if(len==1){ + if(s.charAt(0)==' ') + { + return 0; + } + else{ + return 1; + } + } + for(int i=len-1;i>0;i--){ + if(s.charAt(i)!=' '){ + count++; + if(s.charAt(i-1)==' ') + { + return count; + } + + } + } + if(s.charAt(0)==' ') { + return count; + } + return count+1; + } +} +``` diff --git "a/2018.12.30-leetcode540/540. \346\234\211\345\272\217\346\225\260\347\273\204\344\270\255\347\232\204\345\215\225\344\270\200\345\205\203\347\264\240.md" "b/2018.12.30-leetcode540/540. \346\234\211\345\272\217\346\225\260\347\273\204\344\270\255\347\232\204\345\215\225\344\270\200\345\205\203\347\264\240.md" new file mode 100644 index 000000000..ac471ca4f --- /dev/null +++ "b/2018.12.30-leetcode540/540. \346\234\211\345\272\217\346\225\260\347\273\204\344\270\255\347\232\204\345\215\225\344\270\200\345\205\203\347\264\240.md" @@ -0,0 +1,13 @@ +``` +给定一个只包含整数的有序数组,每个元素都会出现两次,唯有一个数只会出现一次,找出这个数。 + +示例 1: + +输入: [1,1,2,3,3,4,4,8,8] +输出: 2 +示例 2: + +输入: [3,3,7,7,10,11,11] +输出: 10 +注意: 您的方案应该在 O(log n)时间复杂度和 O(1)空间复杂度中运行。 +``` diff --git a/2018.12.30-leetcode540/Ostrichcrab.md b/2018.12.30-leetcode540/Ostrichcrab.md new file mode 100644 index 000000000..91f986ed3 --- /dev/null +++ b/2018.12.30-leetcode540/Ostrichcrab.md @@ -0,0 +1,27 @@ +``` +int x = []() { + std::ios::sync_with_stdio(false); + std::cin.tie(nullptr); + return 0; +}(); +class Solution { +public: + int singleNonDuplicate(vector& nums) { + int size = nums.size(); + int left = 0, right = size-1; + while(left> 1; + if(mid & 1){ + if(nums[mid] == nums[mid-1]) left = mid + 1; + else if(nums[mid] == nums[mid+1]) right = mid - 1; + else return nums[mid]; + }else{ + if(nums[mid] == nums[mid-1]) right = mid - 2; + else if(nums[mid] == nums[mid+1]) left = mid + 2; + else return nums[mid]; + } + } + return nums[left]; + } +}; +``` diff --git a/2018.12.30-leetcode540/TheRocket.md b/2018.12.30-leetcode540/TheRocket.md new file mode 100644 index 000000000..19bacb607 --- /dev/null +++ b/2018.12.30-leetcode540/TheRocket.md @@ -0,0 +1,20 @@ +```java +class Solution { + public int singleNonDuplicate(int[] nums) { + int lo = 0; + int hi = nums.length - 1; + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if ((mid & 1) == 1) { + --mid; + } + if (nums[mid] == nums[mid + 1]) { + lo = mid + 2; + } else { + hi = mid; + } + } + return nums[lo]; + } +} +``` diff --git a/2018.12.30-leetcode540/Tony the Cyclist.md b/2018.12.30-leetcode540/Tony the Cyclist.md new file mode 100644 index 000000000..3c3343d78 --- /dev/null +++ b/2018.12.30-leetcode540/Tony the Cyclist.md @@ -0,0 +1,20 @@ +```python +class Solution(object): + def singleNonDuplicate(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + cot = 1 + pre = nums[0] + for i in range(1, len(nums), 1): + if nums[i] == pre: + cot += 1 + else: + if cot == 1: + return pre + else: + pre = nums[i] + cot = 1 + return nums[-1] +``` diff --git a/2018.12.30-leetcode540/WYJ.md b/2018.12.30-leetcode540/WYJ.md new file mode 100644 index 000000000..086bc8aa1 --- /dev/null +++ b/2018.12.30-leetcode540/WYJ.md @@ -0,0 +1,27 @@ +```java +class Solution { + public int singleNonDuplicate(int[] nums) { + int l = 0, r = nums.length - 1; + while(l < r){ + int mid = l + (r - l) / 2; + if(mid % 2 == 0){ + if(nums[mid] != nums[mid + 1]){ + r = mid; + } + else{ + l = mid + 2; + } + } + else{ + if(nums[mid] == nums[mid - 1]){ + l = mid + 1; + } + else{ + r = mid; + } + } + } + return nums[l]; + } +} +``` diff --git a/2018.12.30-leetcode540/lyan_dut.md b/2018.12.30-leetcode540/lyan_dut.md new file mode 100644 index 000000000..72e580554 --- /dev/null +++ b/2018.12.30-leetcode540/lyan_dut.md @@ -0,0 +1,48 @@ +```c++ +/* + * 540. 有序数组中的单一元素 + * https://leetcode-cn.com/problems/single-element-in-a-sorted-array/ + */ +/* + * 方法一: 二分查找 + */ +int MyLeetCode::singleNonDuplicate(vector &nums) { + int left = 0; + int right = nums.size()-1; + while (left < right){ + int mid = (left+right)/2; + int lremain; + int rremain; + if(nums[mid] == nums[mid-1]){ + lremain = (mid-1) - left; + rremain = right - mid; + if(lremain%2 == 0) + left = mid + 1; + else + right = mid - 2; + } + else if(nums[mid] == nums[mid+1]){ + lremain = mid - left; + rremain = right - (mid+1); + if(rremain%2 == 0) + right = mid - 1; + else + left = mid + 2; + } + else + left = mid; + } + return nums[left]; +} + +/* + * 方法二: 异或 + */ +int MyLeetCode::singleNonDuplicate(vector &nums) { + int res = 0; + for(int i=0; i>1; + if ((mid&1)==1) mid--; + if ( nums[mid] == nums[mid + 1]) { + start = mid + 2;//如果mid是--之后的值,mid+1 mid可能又回到原来的值可能造成死循环 + } else if ( mid-1>=0&&nums[mid] == nums[mid - 1]) { + end=mid-1; + } else { + return nums[mid]; + } + } + return nums[start]; + } +} diff --git "a/2018.12.30-leetcode540/\345\210\230\346\266\246\346\263\275(capture).md" "b/2018.12.30-leetcode540/\345\210\230\346\266\246\346\263\275(capture).md" new file mode 100644 index 000000000..2e05f1846 --- /dev/null +++ "b/2018.12.30-leetcode540/\345\210\230\346\266\246\346\263\275(capture).md" @@ -0,0 +1,29 @@ +```java + public int singleNonDuplicate(int[] nums) { + if (nums.length==1) return nums[0]; + if (nums.length%2==0) return 0; + int mid; + int start=0; + int end=nums.length-1; + while(true){ + mid=(start+end)/2; + if (nums[mid]==nums[mid-1]&&(mid-start)%2==1) { + //该数一定在后面 + if ((end-start)==2) return nums[mid+1]; + start=mid+1; + }else if (nums[mid]==nums[mid+1]&&(mid-start)%2==1) { + //该数一定在前面 + if ((end-start)==2) return nums[mid-1]; + end=mid-1; + }else if (nums[mid]==nums[mid-1]&&(mid-start)%2!=1) { + //该数一定在前面 + end=mid; + }else if (nums[mid]==nums[mid+1]&&(mid-start)%2!=1) { + //该数一定在后面 + start=mid; + }else { + return nums[mid]; + } + } + } +``` diff --git "a/2018.12.30-leetcode540/\345\246\256\345\217\257.md" "b/2018.12.30-leetcode540/\345\246\256\345\217\257.md" new file mode 100644 index 000000000..5234b3655 --- /dev/null +++ "b/2018.12.30-leetcode540/\345\246\256\345\217\257.md" @@ -0,0 +1,58 @@ +``` +package sy190101; + +/** + * @author suyuan + 给定一个只包含整数的有序数组,每个元素都会出现两次,唯有一个数只会出现一次,找出这个数。 + +示例 1: + +输入: [1,1,2,3,3,4,4,8,8] +输出: 2 +示例 2: + +输入: [3,3,7,7,10,11,11] +输出: 10 +注意: 您的方案应该在 O(log n)时间复杂度和 O(1)空间复杂度中运行。 + */ +public class leetcode_540有序数组中的单一元素 +{ + + public static void main(String[] args) + { + int[] nums =new int[] {1,1,2,2,3,3,4,4,8}; + System.out.println(singleNonDuplicate(nums)); + + + } + + public static int singleNonDuplicate2(int[] nums) + { + int left=0; + int right=nums.length-1; + while(left>1; + //奇数 + if((mid&1) !=0) + mid--; + //找到,跳两格 + if(nums[mid]==nums[mid+1]) + left=mid+2; + else + right=mid; + } + return nums[left]; + } + + //无序还可以用异或,有序用有点浪费 + public static int singleNonDuplicate(int[] nums) + { + int res=0; + for(int i=0;i 给定一个只包含整数的有序数组。每个元素都会出现两次,只有一个数只会出现一次,找出这个数。 + +**例子** +> **Example 1:** +Input: [1,1,2,3,3,4,4,8,8] +Output: 2 + +> **Example 2:** +Input: [3,3,7,7,10,11,11] +Output: 10 + +**思想** +法1:异或操作,相同为0,相异为1。但是时间复杂度O(n) +法2:有序数组,考虑二分。 +> 将奇数的mid变为mid-1,而不是偶数的mid+1 → 防止数组越界 + +**解法1** +异或操作 - 时间复杂度O(n),空间复杂度O(1)。 +```python +class Solution(object): + def singleNonDuplicate(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + res = 0 + for num in nums: + res ^= num + return res +``` +**解法2** +二分 - 时间复杂度O(nlogn),空间复杂度O(1)。 +```python +class Solution(object): + def singleNonDuplicate(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + left, right = 0, len(nums) - 1 + while left < right: + mid = (left + right) >> 1 + if mid % 2 == 1: + mid -= 1 # Set the index of mid is 0,2,4... + if nums[mid] != nums[mid+1]: + right = mid + else: + left = mid + 2 + return nums[left] +``` \ No newline at end of file diff --git "a/2018.12.30-leetcode540/\346\243\225\346\246\210\346\240\221.md" "b/2018.12.30-leetcode540/\346\243\225\346\246\210\346\240\221.md" new file mode 100644 index 000000000..07dea677b --- /dev/null +++ "b/2018.12.30-leetcode540/\346\243\225\346\246\210\346\240\221.md" @@ -0,0 +1,20 @@ +``` +class Solution { + public int singleNonDuplicate(int[] nums) { + int start = 0; + int end = nums.length - 1; + while(start false +调用 isBadVersion(5) -> true +调用 isBadVersion(4) -> true + +所以,4 是第一个错误的版本。 +``` diff --git a/2018.12.31-leetcode278/Ostrichcrab.md b/2018.12.31-leetcode278/Ostrichcrab.md new file mode 100644 index 000000000..55cf4174f --- /dev/null +++ b/2018.12.31-leetcode278/Ostrichcrab.md @@ -0,0 +1,18 @@ +``` +// Forward declaration of isBadVersion API. +bool isBadVersion(int version); + +class Solution { +public: + int firstBadVersion(int n) { + int l = 1, r = n; + int mid; + while(l<=r){ + mid = l + (r-l)/2; + if(isBadVersion(mid)) r = mid - 1; + else l = mid + 1; + } + return l; + } +}; +``` diff --git a/2018.12.31-leetcode278/TheRocket.md b/2018.12.31-leetcode278/TheRocket.md new file mode 100644 index 000000000..5738fdd7e --- /dev/null +++ b/2018.12.31-leetcode278/TheRocket.md @@ -0,0 +1,20 @@ +```java +/* The isBadVersion API is defined in the parent class VersionControl. + boolean isBadVersion(int version); */ + +public class Solution extends VersionControl { + public int firstBadVersion(int n) { + int lo = 1; + int hi = n; + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (isBadVersion(mid)) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo; + } +} +``` diff --git a/2018.12.31-leetcode278/WYJ.md b/2018.12.31-leetcode278/WYJ.md new file mode 100644 index 000000000..46038633c --- /dev/null +++ b/2018.12.31-leetcode278/WYJ.md @@ -0,0 +1,17 @@ +```java +public class Solution extends VersionControl { + public int firstBadVersion(int n) { + int l = 1, r = n; + while(l < r){ + int mid = l + (r - l) / 2; + if(isBadVersion(mid)){ + r = mid; + } + else{ + l = mid + 1; + } + } + return l; + } +} +``` diff --git a/2018.12.31-leetcode278/sourcema.md b/2018.12.31-leetcode278/sourcema.md new file mode 100644 index 000000000..7478df027 --- /dev/null +++ b/2018.12.31-leetcode278/sourcema.md @@ -0,0 +1,15 @@ +# LeetCode 278 + public class Solution extends VersionControl { + public int firstBadVersion(int n) { + int left=1; + int right=n; + while(left 你是PM且现在领导团队开发一个新产品。不幸的是,最新版的产品有质量问题。因为每个版本都是基于上个版本产品开发的,所以质量差的产品会延续给下一代产品。 +假设你有n代产品[1, 2, ..., n],想找到第一个坏的版本。 + +> 给定一个API名为 isBadVersion(version),返回version是否是坏的。编写函数找到第一个坏的版本。(最小化调用API的次数) + +**例子** +> Given n = 5, and version = 4 is the first bad version. +call isBadVersion(3) -> false +call isBadVersion(5) -> true +call isBadVersion(4) -> true +Then 4 is the first bad version. + +**思想** +二分,找到第一个为 isBadVersion(version)返回为true的版本。 + +**解法** +```python +# The isBadVersion API is already defined for you. +# @param version, an integer +# @return a bool +# def isBadVersion(version): + +class Solution(object): + def firstBadVersion(self, n): + """ + :type n: int + :rtype: int + """ + l, r = 1, n + while l <= r: + mid = (l + r) >> 1 + if isBadVersion(mid): + if mid == 1 or not isBadVersion(mid-1): + return mid + r = mid - 1 + else: + l = mid + 1 +``` \ No newline at end of file diff --git a/2018.12.4-leetcode101/-.md b/2018.12.4-leetcode101/-.md new file mode 100644 index 000000000..8777ca6d5 --- /dev/null +++ b/2018.12.4-leetcode101/-.md @@ -0,0 +1,29 @@ + +public class Solution_101 { + public boolean isSymmetric(TreeNode root) { + if (root == null) { + return false; + } + return isSymmetric(root.left,root.right); + } + public boolean isSymmetric(TreeNode left,TreeNode right) { + if(left == null && right == null) + return true; + if((left!=null&&right==null)||(left==null&&right!=null)) + return false; + if(left.val == right.val) + return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); + else + return false; + } + + class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } + } +} diff --git a/2018.12.4-leetcode101/1.md b/2018.12.4-leetcode101/1.md new file mode 100644 index 000000000..e1476cfc2 --- /dev/null +++ b/2018.12.4-leetcode101/1.md @@ -0,0 +1 @@ +sd diff --git a/2018.12.4-leetcode101/FFFro.md b/2018.12.4-leetcode101/FFFro.md new file mode 100644 index 000000000..573c71d45 --- /dev/null +++ b/2018.12.4-leetcode101/FFFro.md @@ -0,0 +1,20 @@ +class Solution { + public boolean isSymmetric(TreeNode root) { + if (root == null){ + return true; + }else { + return isSymmetric(root.left,root.right); + } + } + + private boolean isSymmetric(TreeNode left, TreeNode right) { + if (left == null && right == null){ + return true; + }else if (left == null || right == null){ + return false; + } + if (left.val != right.val) + return false; + return isSymmetric(left.left,right.right) && isSymmetric(left.right,right.left); + } +} diff --git a/2018.12.4-leetcode101/GatesMa.md b/2018.12.4-leetcode101/GatesMa.md new file mode 100644 index 000000000..c3f9654d9 --- /dev/null +++ b/2018.12.4-leetcode101/GatesMa.md @@ -0,0 +1,23 @@ +# c++ +```cpp +/** + * 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: + bool isSymmetric(TreeNode* root) { + return isMirror(root, root); + } + bool isMirror(TreeNode *t1, TreeNode *t2){ + if(t1 == NULL && t2 == NULL) return true; + if(t1 == NULL || t2 == NULL) return false; + return (t1->val == t2->val) && isMirror(t1->left, t2->right) && isMirror(t1->right, t2->left); + } +}; +``` diff --git a/2018.12.4-leetcode101/Ostrichcrab.md b/2018.12.4-leetcode101/Ostrichcrab.md new file mode 100644 index 000000000..6e0e47948 --- /dev/null +++ b/2018.12.4-leetcode101/Ostrichcrab.md @@ -0,0 +1,23 @@ +``` +/** + * 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: + bool isSymmetric(TreeNode* root) { + return isMirror(root,root); + } + bool isMirror(TreeNode* root1, TreeNode* root2){ + if(root1==nullptr && root2==nullptr) return true; + if(root1==nullptr || root2==nullptr) return false; + if(root1->val != root2->val) return false; + return isMirror(root1->left,root2->right) && isMirror(root1->right,root2->left); + } +}; +``` diff --git a/2018.12.4-leetcode101/Sagittarius.md b/2018.12.4-leetcode101/Sagittarius.md new file mode 100644 index 000000000..8955c276f --- /dev/null +++ b/2018.12.4-leetcode101/Sagittarius.md @@ -0,0 +1,35 @@ +``` +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +bool isSymmetric1(TreeNode* r1,TreeNode* r2) +{ + if(!r1&&!r2) + return true; + else if((r1&&!r2)||(!r1&&r2)) + return false; + else + { + if(r1->val!=r2->val) + return false; + else + return isSymmetric1(r1->left,r2->right)&&isSymmetric1(r1->right,r2->left); + } + +} +class Solution { +public: + bool isSymmetric(TreeNode* root) { + if(!root) + return true; + else + return isSymmetric1(root->left,root->right); + } +}; +``` diff --git a/2018.12.4-leetcode101/Sunny.md b/2018.12.4-leetcode101/Sunny.md new file mode 100644 index 000000000..da42c0712 --- /dev/null +++ b/2018.12.4-leetcode101/Sunny.md @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if (root == null) return true; + return isSymmetric(root.left, root.right); + } + + public boolean isSymmetric(TreeNode node1, TreeNode node2) { + if (node1 == null && node2 == null) return true; + if ((node1 == null) ^ (node2 == null)) return false; + if (node1.val != node2.val) return false; + return isSymmetric(node1.left, node2.right) && isSymmetric(node1.right, node2.left); + } +} diff --git a/2018.12.4-leetcode101/TheRocket.md b/2018.12.4-leetcode101/TheRocket.md new file mode 100644 index 000000000..68f3f7e0d --- /dev/null +++ b/2018.12.4-leetcode101/TheRocket.md @@ -0,0 +1,63 @@ +```java +// 递归 +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + return root == null || isSymmetric(root.left, root.right); + } + + public boolean isSymmetric(TreeNode left, TreeNode right) { + if (left == null || right == null) { + return left == right; + } + return left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); + } +} + +// 迭代 +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if (root == null) { + return true; + } + LinkedList stack = new LinkedList<>(); + stack.push(root.left); + stack.push(root.right); + while (!stack.isEmpty()) { + TreeNode right = stack.pop(); + TreeNode left = stack.pop(); + if (left == null && right == null) { + continue; + } + if (left == null || right == null) { + return false; + } + if (left.val != right.val) { + return false; + } + stack.push(left.left); + stack.push(right.right); + stack.push(left.right); + stack.push(right.left); + } + return true; + } +} +``` diff --git a/2018.12.4-leetcode101/halfofwater.md b/2018.12.4-leetcode101/halfofwater.md new file mode 100644 index 000000000..2cb991c31 --- /dev/null +++ b/2018.12.4-leetcode101/halfofwater.md @@ -0,0 +1,67 @@ +## Leetcode 101 + + +### 递归解法: + +``` C++ +/** + * 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: + bool isSymmetric(TreeNode* root) { + return helper(root, root); + } + bool helper(TreeNode *left, TreeNode *right) { + if (left == NULL && right == NULL) return true; + if (left == NULL || right == NULL) return false; + + if (left->val != right->val) return false; + return helper(left->left, right->right) && helper(left->right, right->left); + +} +}; + +``` + +### 迭代解法: +``` C++ +/** + * 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: + bool isSymmetric(TreeNode* root) { + std::queue q; + q.push(root); + q.push(root); + while (!q.empty()) { + TreeNode* t1 = q.front(); + q.pop(); + TreeNode* t2 = q.front(); + q.pop(); + if (t1 == NULL && t2 == NULL) continue; + if (t1 == NULL || t2 == NULL) return false; + if (t1->val != t2->val) return false; + q.push(t1->left); + q.push(t2->right); + q.push(t1->right); + q.push(t2->left); + } + return true; + } +}; + +``` diff --git a/2018.12.4-leetcode101/linyk3.md b/2018.12.4-leetcode101/linyk3.md new file mode 100644 index 000000000..7cf157293 --- /dev/null +++ b/2018.12.4-leetcode101/linyk3.md @@ -0,0 +1,56 @@ + 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; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if(root == null) { + return true; + } + return isSymmetric(root.left, root.right); + } + + public boolean isSymmetric(TreeNode left, TreeNode right){ + if(left == null && right == null){ + return true; + } + if(left == null || right == null) { + return false; + } + if(left.val != right.val){ + return false; + } + return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); + } +} diff --git a/2018.12.4-leetcode101/oven123.md b/2018.12.4-leetcode101/oven123.md new file mode 100644 index 000000000..ef2b18775 --- /dev/null +++ b/2018.12.4-leetcode101/oven123.md @@ -0,0 +1,30 @@ +```java + +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + + return compareTree(root,root); + } + boolean compareTree(TreeNode tree1,TreeNode tree2){ + if(tree1==null&&tree2==null)//递归到最内层同时为空 + return true; + if(tree1==null||tree2==null)//如果有其中一个为空但另一个不为空 + return false; + return(tree1.val==tree2.val) + &&compareTree(tree1.left,tree2.right) + &&compareTree(tree1.right,tree2.left); + + + } +} + +``` diff --git a/2018.12.4-leetcode101/zjukk.md b/2018.12.4-leetcode101/zjukk.md new file mode 100644 index 000000000..bd30f5b9e --- /dev/null +++ b/2018.12.4-leetcode101/zjukk.md @@ -0,0 +1,15 @@ +``` +class Solution { +public: + bool isSymmetric(TreeNode* root) { + if (!root) return true; + return help(root->left,root->right); + } + bool help(TreeNode* left, TreeNode* right) { + if (!left && !right) return true; + if ((!left && right) || (left && !right)) return false; + if (left->val != right->val) return false; + else return help(left->left,right->right) && help(left->right,right->left); + } +}; +``` diff --git "a/2018.12.4-leetcode101/\343\200\202\343\200\202\343\200\202.md" "b/2018.12.4-leetcode101/\343\200\202\343\200\202\343\200\202.md" new file mode 100644 index 000000000..8ad58b98c --- /dev/null +++ "b/2018.12.4-leetcode101/\343\200\202\343\200\202\343\200\202.md" @@ -0,0 +1,24 @@ +``` +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if(root == null)return true; + return isSymmetric2(root.left,root.right); + } + + private boolean isSymmetric2(TreeNode left, TreeNode right) { + if (left != null && right != null && left.val == right.val){ + return isSymmetric2(left.left,right.right) && isSymmetric2(left.right,right.left); + } + return (left==null && right == null); + } +} +``` diff --git "a/2018.12.4-leetcode101/\344\272\221\346\272\252101.md" "b/2018.12.4-leetcode101/\344\272\221\346\272\252101.md" new file mode 100644 index 000000000..b39f9f561 --- /dev/null +++ "b/2018.12.4-leetcode101/\344\272\221\346\272\252101.md" @@ -0,0 +1,21 @@ +bool isSymmetricHelp(struct TreeNode* left,struct TreeNode* right); +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ +bool isSymmetric(struct TreeNode* root) +{ + return root==NULL|| isSymmetricHelp(root->left,root->right); +} +bool isSymmetricHelp(struct TreeNode* left,struct TreeNode* right) +{ + if(left==NULL||right==NULL) + return left==right; + if(left->val==right->val&&isSymmetricHelp(left->left,right->right)&&isSymmetricHelp(left->right,right->left)) + return true; + return false; +} diff --git "a/2018.12.4-leetcode101/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" "b/2018.12.4-leetcode101/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" new file mode 100644 index 000000000..8fc6891d7 --- /dev/null +++ "b/2018.12.4-leetcode101/\345\210\251\347\210\252\345\276\267\351\262\201\344\274\212.md" @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if(root == null) return true; + return isSymmetric(root.left, root.right); + } + + private boolean isSymmetric(TreeNode left, TreeNode right) { + if(left == null && right == null) { + return true; + } + if(left == null || right == null) { + return false; + } + return isSymmetric(left.left, right.right) && + isSymmetric(left.right, right.left) && + left.val == right.val; + } +} diff --git "a/2018.12.4-leetcode101/\345\225\246\345\225\246\345\225\246.md" "b/2018.12.4-leetcode101/\345\225\246\345\225\246\345\225\246.md" new file mode 100644 index 000000000..c4bc845f4 --- /dev/null +++ "b/2018.12.4-leetcode101/\345\225\246\345\225\246\345\225\246.md" @@ -0,0 +1,30 @@ +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + Queue q = new LinkedList<>(); + q.add(root); + q.add(root); + while(!q.isEmpty()){ + TreeNode r1=q.poll(); + TreeNode r2=q.poll(); + if(r1==null&&r2==null)continue; + if(r1==null||r2==null)return false; + if(r1.val!=r2.val)return false; + q.add(r1.left); + q.add(r2.right); + q.add(r1.right); + q.add(r2.left); + } + return true; + } +} +``` diff --git "a/2018.12.4-leetcode101/\345\256\266.md" "b/2018.12.4-leetcode101/\345\256\266.md" new file mode 100644 index 000000000..8f9a2c69d --- /dev/null +++ "b/2018.12.4-leetcode101/\345\256\266.md" @@ -0,0 +1,11 @@ +``` +func isSymmetric(root *TreeNode) bool { + return isw(root,root) +} +func isw (left *TreeNode,right *TreeNode) bool{ + if left == nil && right == nil {return true} + if left == nil || right == nil{return false} + return left.Val == right.Val && isw(left.Left,right.Right)&&isw(left.Right,right.Left) +} + +``` diff --git "a/2018.12.4-leetcode101/\345\274\240\345\260\217\350\203\226.md" "b/2018.12.4-leetcode101/\345\274\240\345\260\217\350\203\226.md" new file mode 100644 index 000000000..f9e8eb785 --- /dev/null +++ "b/2018.12.4-leetcode101/\345\274\240\345\260\217\350\203\226.md" @@ -0,0 +1,25 @@ + /** + 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: + bool isSymmetric(TreeNode* root){ + if(root==0) + return true; + return CompareNodes(root->left,root->right); + } + public: + bool CompareNodes(TreeNode* node1,TreeNode* node2){ + if(node1==0&&node2==0) return true; + if(node1==0||node2==0) return false; + if(node1->val!=node2->val) return false; + else + return CompareNodes(node1->left,node2->right)&&CompareNodes(node1->right,node2->left); + } + }; diff --git "a/2018.12.4-leetcode101/\350\216\216\350\216\216.md" "b/2018.12.4-leetcode101/\350\216\216\350\216\216.md" new file mode 100644 index 000000000..bdc191bb6 --- /dev/null +++ "b/2018.12.4-leetcode101/\350\216\216\350\216\216.md" @@ -0,0 +1,31 @@ +``` +class Solution: + def isSymmetric(self, root): + """ + :type root: TreeNode + :rtype: bool + """ + if root == None: + return True + elif root.left == None and root.right == None: + return True + d = deque([]) + d.append(root.right) + d.appendleft(root.left) + while d: + rightnode = d.pop() + leftnode = d.popleft() + if rightnode == None and leftnode == None: + pass + elif rightnode == None or leftnode == None: + return False + else: + if rightnode.val == leftnode.val: + d.append(rightnode.right) + d.appendleft(leftnode.left) + d.append(rightnode.left) + d.appendleft(leftnode.right) + else: + return False + return True +``` diff --git "a/2019.01.01-leetcode153/153.\346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227.md" "b/2019.01.01-leetcode153/153.\346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227.md" new file mode 100644 index 000000000..2d084ac84 --- /dev/null +++ "b/2019.01.01-leetcode153/153.\346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227.md" @@ -0,0 +1,18 @@ +``` +假设按照升序排序的数组在预先未知的某个点上进行了旋转。 + +( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 + +请找出其中最小的元素。 + +你可以假设数组中不存在重复元素。 + +示例 1: + +输入: [3,4,5,1,2] +输出: 1 +示例 2: + +输入: [4,5,6,7,0,1,2] +输出: 0 +``` diff --git a/2019.01.01-leetcode153/Ostrichcrab.md b/2019.01.01-leetcode153/Ostrichcrab.md new file mode 100644 index 000000000..8c07e6eff --- /dev/null +++ b/2019.01.01-leetcode153/Ostrichcrab.md @@ -0,0 +1,17 @@ +``` +class Solution { +public: + int findMin(vector& nums) { + int l = 0; + int r = nums.size()-1; + int mid = 0; + while(l>1; + if(nums[mid]>nums[r]) l = mid+1; + else r = mid; + } + return nums[r]; + } +}; +``` diff --git a/2019.01.01-leetcode153/TheRocket.md b/2019.01.01-leetcode153/TheRocket.md new file mode 100644 index 000000000..0c47ba604 --- /dev/null +++ b/2019.01.01-leetcode153/TheRocket.md @@ -0,0 +1,17 @@ +```java +class Solution { + public int findMin(int[] nums) { + int lo = 0; + int hi = nums.length - 1; + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (nums[mid] > nums[hi]) { + lo = mid + 1; + } else { + hi = mid; + } + } + return nums[lo]; + } +} +``` diff --git a/2019.01.01-leetcode153/Tony the Cyclist.md b/2019.01.01-leetcode153/Tony the Cyclist.md new file mode 100644 index 000000000..8e31acb93 --- /dev/null +++ b/2019.01.01-leetcode153/Tony the Cyclist.md @@ -0,0 +1,9 @@ +```python +class Solution(object): + def findMin(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + return min(nums) +``` diff --git a/2019.01.01-leetcode153/WYJ.md b/2019.01.01-leetcode153/WYJ.md new file mode 100644 index 000000000..9e464d055 --- /dev/null +++ b/2019.01.01-leetcode153/WYJ.md @@ -0,0 +1,17 @@ +```java +class Solution { + public int findMin(int[] nums) { + int l = 0, r = nums.length - 1; + while(l < r){ + int mid = l + (r - l) / 2; + if(nums[mid] > nums[r]){ + l = mid + 1; + } + else{ + r = mid; + } + } + return nums[l]; + } +} +``` diff --git a/2019.01.01-leetcode153/marguerite.md b/2019.01.01-leetcode153/marguerite.md new file mode 100644 index 000000000..33b754fdf --- /dev/null +++ b/2019.01.01-leetcode153/marguerite.md @@ -0,0 +1,22 @@ + +``` +class Solution { +public: + int findMin(vector &num) { + int start = 0; + int end = num.size() - 1; + int mid = 0; + while (start < end) { //注意这里和普通的二分查找不同,这里是start < end不是 start <= end. + mid = start + (end - start)/2; + if (num[mid] > num[end]) + start = mid + 1; //此时可以扔掉mid的值 + else + end = mid;//此时不能扔掉mid的值 + } + return num[end]; //退出循环说明start与end相等,所以只剩一个元素可能,所以return [start]或者return [end]都可以了。 + //注意不能return mid,可以从{2,1}这个输入看出来。 + + } + + ``` + diff --git a/2019.01.01-leetcode153/sourcema.md b/2019.01.01-leetcode153/sourcema.md new file mode 100644 index 000000000..a760fb24a --- /dev/null +++ b/2019.01.01-leetcode153/sourcema.md @@ -0,0 +1,18 @@ +# LeetCode 153 + class Solution { + public int findMin(int[] nums) {//典型的二分,数组进行了旋转,我们现在把数组分为两部分, + // 前面部分是数组中元素较大的元素,后面部分呢是数组中元素较小的元素,如果中间部分的元素值大于首元素和 + //末尾元素说明当前位置在数组的前半部分,left应该等于mid+1,否则说明在数组后半部分right==mid; + int left=0; + int right=nums.length-1; + while (left < right && nums[left] > nums[right]) { + int mid=(left+right)>>1; + if (nums[mid] >= nums[left] && nums[right] < nums[mid]) { + left = mid + 1; + } else { + right=mid; + } + } + return nums[left]; + } +} diff --git "a/2019.01.01-leetcode153/\346\235\216\347\242\247\346\266\265.md" "b/2019.01.01-leetcode153/\346\235\216\347\242\247\346\266\265.md" new file mode 100644 index 000000000..b428ecd11 --- /dev/null +++ "b/2019.01.01-leetcode153/\346\235\216\347\242\247\346\266\265.md" @@ -0,0 +1,38 @@ +#### [153. Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) +**题目描述** +> 假设按照升序排序的数组,在预先未知的某个点上进行了旋转。 +( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 + +> 请找出其中最小的元素。(假设数组中不存在重复元素) + +**例子** +> **Example 1:** +Input: [3,4,5,1,2] +Output: 1 + +> **Example 2:** +Input: [4,5,6,7,0,1,2] +Output: 0 + +**思想** +若旋转了,则num[l] > num[r];否则未旋转,直接返回num[l]。 +>当nums[mid] > nums[r]时,mid在未旋转部分,取l = mid + 1; +否则,mid在旋转部分,取r = mid; + +**解法** +```python +class Solution(object): + def findMin(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + l, r = 0, len(nums)-1 + while l < r and nums[l] > nums[r]: + mid = (l + r) >> 1 + if nums[mid] > nums[r]: # 肯定未旋转,取左侧 + l = mid + 1 + else: # 肯定旋转了,取右侧 + r = mid + return nums[l] +``` \ No newline at end of file diff --git "a/2019.01.01-leetcode153/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2019.01.01-leetcode153/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..94e0cdd37 --- /dev/null +++ "b/2019.01.01-leetcode153/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,20 @@ +``` +class Solution { +public: + int findMin(vector& nums) { + if(nums.size() <= 1) return nums[0]; + + int i = 0; + int j = 1; + while(j < nums.size()) + { + if(nums[i] > nums[j]) + return nums[j]; + i++; + j++; + } + + return nums[0]; + } +}; +``` diff --git a/2019.01.02-leetcode34/Ostrichcrab.md b/2019.01.02-leetcode34/Ostrichcrab.md new file mode 100644 index 000000000..43478ea2b --- /dev/null +++ b/2019.01.02-leetcode34/Ostrichcrab.md @@ -0,0 +1,28 @@ +``` +class Solution { +public: + vector searchRange(vector& nums, int target) { + vector ans(2,-1); + int size = nums.size(); + if(!size) return ans; + int l = 0, r = size-1; + int mid = -1; + if(targetnums[r]) return ans; + while(l<=r) + { + mid = (l+r)>>1; + if(nums[mid]==target){ + int pos = mid; + while(nums[pos]==target && pos-1) mid--; + ans[0] = mid+1; + return ans; + } + else if(nums[mid] < target) l = mid+1; + else r = mid-1; + } + return ans; + } +}; +``` diff --git a/2019.01.02-leetcode34/TheRocket.md b/2019.01.02-leetcode34/TheRocket.md new file mode 100644 index 000000000..b86f3139a --- /dev/null +++ b/2019.01.02-leetcode34/TheRocket.md @@ -0,0 +1,40 @@ +```java +class Solution { + public int[] searchRange(int[] nums, int target) { + int left = lowerBound(nums, target); + if (left < nums.length && nums[left] == target) { + int right = upperBound(nums, target); + return new int[] { left, right - 1 }; + } + return new int[] { -1, -1 }; + } + + private int lowerBound(int[] nums, int target) { + int lo = 0; + int hi = nums.length; + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (nums[mid] < target) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } + + private int upperBound(int[] nums, int target) { + int lo = 0; + int hi = nums.length; + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (nums[mid] <= target) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } +} +``` diff --git a/2019.01.02-leetcode34/Tony the Cyclist.md b/2019.01.02-leetcode34/Tony the Cyclist.md new file mode 100644 index 000000000..a313fb67b --- /dev/null +++ b/2019.01.02-leetcode34/Tony the Cyclist.md @@ -0,0 +1,15 @@ +```python +class Solution(object): + def searchRange(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ + if target not in nums: + return [-1, -1] + begin = nums.index(target) + nums.reverse() + end = len(nums) - 1 - nums.index(target) + return [begin, end] +``` diff --git a/2019.01.02-leetcode34/WYJ.md b/2019.01.02-leetcode34/WYJ.md new file mode 100644 index 000000000..0000bed58 --- /dev/null +++ b/2019.01.02-leetcode34/WYJ.md @@ -0,0 +1,38 @@ +```java +class Solution { + public int[] searchRange(int[] nums, int target) { + if(nums.length == 0){ + return new int[] {-1, -1}; + } + int l = 0, r = nums.length - 1; + while(l < r){ + int mid = l + (r - l) / 2; + if(nums[mid] < target){ + l = mid + 1; + } + else{ + r = mid; + } + } + int start = l; + if(nums[l] == target){ + r = nums.length - 1; + while(l < r){ + int mid = l + (r - l) / 2; + if(mid == l){ + mid += 1; + } + if(nums[mid] > target){ + r = mid - 1; + } + else{ + l = mid; + } + } + int end = r; + return new int[] {start, end}; + } + return new int[] {-1, -1}; + } +} +``` diff --git a/2019.01.02-leetcode34/marguerite.md b/2019.01.02-leetcode34/marguerite.md new file mode 100644 index 000000000..8ad7353fe --- /dev/null +++ b/2019.01.02-leetcode34/marguerite.md @@ -0,0 +1,43 @@ +``` +class Solution { + public int[] searchRange(int[] nums, int target) { + int l=0; + int h=nums.length-1; + int answer[]=new int[2]; + int s=-1; + int e=-1; + int t=-1; + while(l<=h){ + int m=(l+h)/2; + if(nums[m]>target) + h=m-1; + else if(nums[m]=0&&nums[s]==target){ + s--; + } + while(e<=nums.length-1&&nums[e]==target){ + e++; + } + s=s+1; + e=e-1; + answer[0]=s; + answer[1]=e; + + } + return answer; + } +} + +``` diff --git a/2019.01.02-leetcode34/sourcema.md b/2019.01.02-leetcode34/sourcema.md new file mode 100644 index 000000000..d579a4cba --- /dev/null +++ b/2019.01.02-leetcode34/sourcema.md @@ -0,0 +1,52 @@ +# LeetCode 34 + class Solution { + public int[] searchRange(int[] nums, int target) { + int[] res = {-1, -1}; + if (nums == null || nums.length == 0) { + return res; + } + int start=findStartPosition(nums, target); + int end=findEndPosition(nums, target); + res[0]=start; + res[1]=end; + return res; + } + private static int findEndPosition(int[] nums, int target) { + int left=0; + int right=nums.length-1; + while (left < right) { + int mid=left+(right-left)/2; + if (nums[mid] < target) { + left=mid+1; + } else if (nums[mid] > target) { + right=mid-1; + } else { + if (nums[mid + 1] != nums[mid]) { + return mid; + } else { + left=mid+1; + } + } + } + return nums[left]!=target?-1:left; + } + private static int findStartPosition(int[] nums, int target) { + int left=0; + int right=nums.length-1; + while (left < right) { + int mid=left+(right-left)/2; + if (nums[mid] < target) { + left=mid+1; + } else if (nums[mid] > target) { + right=mid-1; + } else { + if (mid==0||nums[mid - 1] != nums[mid]) { + return mid; + } else { + right=mid-1; + } + } + } + return nums[left]!=target?-1:left; + } +} diff --git "a/2019.01.02-leetcode34/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.02-leetcode34/\345\210\230\346\266\246\346\263\275(capture).md" new file mode 100644 index 000000000..2d5e54abe --- /dev/null +++ "b/2019.01.02-leetcode34/\345\210\230\346\266\246\346\263\275(capture).md" @@ -0,0 +1,40 @@ +```java + public static int[] searchRange(int[] nums, int target) { + + if (nums.length==0) return new int[]{-1,-1}; + int start=0; + int end=nums.length-1; + int mid; + while (start<=end){ + mid=start+(end-start)/2; + if (nums[mid]>target){ + end=mid-1; + continue; + } + if (nums[mid]0&&nums[left]==nums[left-1]){ + left=left-1; + continue; + } + break; + } + while (true){ + + if (right 给定一个按照升序排列的整数数组 nums和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 + +> 你的算法时间复杂度必须是 O(log n) 级别。 +如果数组中不存在目标值,返回 [-1, -1]。 + +**例子** +> **Example 1:** +Input: nums = [5,7,7,8,8,10], target = 8 +Output: [3,4] + +> **Example 2:** +Input: nums = [5,7,7,8,8,10], target = 6 +Output: [-1,-1] + +**思想** +二分。方法多样化:getFirst用的非递归,getLast用的递归。 + +**解法** +```python +class Solution(object): + def searchRange(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ + return [self.getFirst(nums, target), self.getLast(nums, target, 0, len(nums)-1)] + + def getFirst(self, nums, target): + l, r = 0, len(nums) - 1 + while l <= r: + mid = (l + r) >> 1 + if nums[mid] < target: + l = mid + 1 + elif nums[mid] > target: + r = mid - 1 + else: + if mid == 0 or nums[mid-1] < target: + return mid + r = mid - 1 + return -1 + + def getLast(self, nums, target, l, r): + if l > r: + return -1 + + mid = (l + r) >> 1 + if nums[mid] < target: + return self.getLast(nums, target, mid+1, r) + if nums[mid] > target: + return self.getLast(nums, target, l, mid-1) + if mid == len(nums)-1 or nums[mid+1] > target: + return mid + return self.getLast(nums, target, mid+1, r) +``` \ No newline at end of file diff --git "a/2019.01.02-leetcode34/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2019.01.02-leetcode34/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..814ed43fa --- /dev/null +++ "b/2019.01.02-leetcode34/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,33 @@ +``` +class Solution { +public: + vector searchRange(vector& nums, int target) { + + int l = 0; + int r = nums.size()-1; + while(l <= r) + { + int mid = l + (r-l)/2; + if(nums[mid] == target) + { + int i=mid; + int j=mid; + while(i>0 && nums[i-1]==target) + i--; + while(j{i, j}; + } + else if(nums[mid] > target) + { + r = mid-1; + } + else + l = mid + 1; + } + + return vector{-1, -1}; + } +}; +``` diff --git a/2019.01.03-leetcode241/Ostrichcrab.md b/2019.01.03-leetcode241/Ostrichcrab.md new file mode 100644 index 000000000..7c6da7d24 --- /dev/null +++ b/2019.01.03-leetcode241/Ostrichcrab.md @@ -0,0 +1,25 @@ +``` +class Solution { +public: + vector diffWaysToCompute(string input) { + vector result; + for(int i = 0; i < input.size(); i++){ + char c = input[i]; + if(c=='+' || c=='-' || c=='*'){ + auto result1 = diffWaysToCompute(input.substr(0,i)); + auto result2 = diffWaysToCompute(input.substr(i+1)); + for(int r1 : result1){ + for(int r2 : result2){ + if(c=='+') result.push_back(r1+r2); + else if(c=='-') result.push_back(r1-r2); + else result.push_back(r1*r2); + } + } + } + } + if(result.empty()) + result.push_back(atoi(input.c_str())); + return result; + } +}; +``` diff --git a/2019.01.03-leetcode241/TheRocket.md b/2019.01.03-leetcode241/TheRocket.md new file mode 100644 index 000000000..848ab54c4 --- /dev/null +++ b/2019.01.03-leetcode241/TheRocket.md @@ -0,0 +1,29 @@ +```java +class Solution { + public List diffWaysToCompute(String input) { + List res = new ArrayList<>(); + for (int i = 0; i < input.length(); ++i) { + char c = input.charAt(i); + if (c == '+' || c == '-' || c == '*') { + List left = diffWaysToCompute(input.substring(0, i)); + List right = diffWaysToCompute(input.substring(i + 1)); + for (int l : left) { + for (int r : right) { + if (c == '+') { + res.add(l + r); + } else if (c == '-') { + res.add(l - r); + } else { + res.add(l * r); + } + } + } + } + } + if (res.size() == 0) { + res.add(Integer.valueOf(input)); + } + return res; + } +} +``` diff --git a/2019.01.03-leetcode241/marguerite.md b/2019.01.03-leetcode241/marguerite.md new file mode 100644 index 000000000..4020d3855 --- /dev/null +++ b/2019.01.03-leetcode241/marguerite.md @@ -0,0 +1,32 @@ +``` +class Solution { +public: + vector diffWaysToCompute(string input) { + vector ret; + for(int i = 0; i < input.size(); i ++) + { + if(input[i] == '+' || input[i] == '-' || input[i] == '*') + { + vector left = diffWaysToCompute(input.substr(0, i)); + vector right = diffWaysToCompute(input.substr(i+1)); + for(int j = 0; j < left.size(); j ++) + { + for(int k = 0; k < right.size(); k ++) + { + if(input[i] == '+') + ret.push_back(left[j] + right[k]); + else if(input[i] == '-') + ret.push_back(left[j] - right[k]); + else + ret.push_back(left[j] * right[k]); + } + } + } + } + if(ret.empty()) + ret.push_back(atoi(input.c_str())); + return ret; + } +}; + +``` diff --git a/2019.01.03-leetcode241/sourcema.md b/2019.01.03-leetcode241/sourcema.md new file mode 100644 index 000000000..ecdffcd7e --- /dev/null +++ b/2019.01.03-leetcode241/sourcema.md @@ -0,0 +1,26 @@ +# leetcode 241 + public List diffWaysToCompute(String input) { + List res=new ArrayList(); + for(int i=0;i left=diffWaysToCompute(input.substring(0,i)); + List right=diffWaysToCompute(input.substring(i+1,input.length())); + for(Integer l:left){ + for(Integer r:right){ + switch (ch) + { + case '*':res.add(l*r); break; + case '-':res.add(l-r); break; + case '+':res.add(l+r); break; + } + } + } + } + } + if(res.size()==0){ + res.add(Integer.valueOf(input)); + return res; + } + return res; + } diff --git "a/2019.01.03-leetcode241/\344\270\272\350\277\220\347\256\227\350\241\250\350\276\276\345\274\217\350\256\276\350\256\241\344\274\230\345\205\210\347\272\247" "b/2019.01.03-leetcode241/\344\270\272\350\277\220\347\256\227\350\241\250\350\276\276\345\274\217\350\256\276\350\256\241\344\274\230\345\205\210\347\272\247" new file mode 100644 index 000000000..24f632383 --- /dev/null +++ "b/2019.01.03-leetcode241/\344\270\272\350\277\220\347\256\227\350\241\250\350\276\276\345\274\217\350\256\276\350\256\241\344\274\230\345\205\210\347\272\247" @@ -0,0 +1,19 @@ +给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。 + +示例 1: + +输入: "2-1-1" +输出: [0, 2] +解释: +((2-1)-1) = 0 +(2-(1-1)) = 2 +示例 2: + +输入: "2*3-4*5" +输出: [-34, -14, -10, -10, 10] +解释: +(2*(3-(4*5))) = -34 +((2*3)-(4*5)) = -14 +((2*(3-4))*5) = -10 +(2*((3-4)*5)) = -10 +(((2*3)-4)*5) = 10 diff --git "a/2019.01.03-leetcode241/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.03-leetcode241/\345\210\230\346\266\246\346\263\275(capture).md" new file mode 100644 index 000000000..a642fd012 --- /dev/null +++ "b/2019.01.03-leetcode241/\345\210\230\346\266\246\346\263\275(capture).md" @@ -0,0 +1,32 @@ +```java + public List diffWaysToCompute1(String input) { + List res = new ArrayList<>(); + for (int i=0;i left = diffWaysToCompute1(input.substring(0,i)); + List right = diffWaysToCompute1(input.substring(i+1)); + + for (int j=0;j 给定一个含有数字和运算符的字符串,为表达式**添加括号**,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。 + +**例子** +> **示例 1**: +输入: "2-1-1" +输出: [0, 2] +解释: +((2-1)-1) = 0 +(2-(1-1)) = 2 + +> **示例 2:** +输入: "2*3-4*5" +输出: [-34, -14, -10, -10, 10] +解释: +(2*(3-(4*5))) = -34 +((2*3)-(4*5)) = -14 +((2*(3-4))*5) = -10 +(2*((3-4)*5)) = -10 +(((2*3)-4)*5) = 10 + +**思想** +分治法 +1)递归地将表达式**按照运算符拆分**为左右两半; +2)分解成子问题,用操作符继续分成左右两部分; +3)截止条件:isdigit() +可采用dic存储优化 + +**解法** +```python +class Solution(object): + def diffWaysToCompute(self, input): + """ + :type input: str + :rtype: List[int] + """ + self.dic = {} + return self.helper(input) + + def helper(self, input): + if input in self.dic: + return self.dic[input] + if input.isdigit(): + return [int(input)] + + res = [] + for i in range(len(input)): + if input[i] in '+-*': + l = self.diffWaysToCompute(input[:i]) + r = self.diffWaysToCompute(input[i+1:]) + + for x in l: + for y in r: + if input[i] == '+': + res.append(x + y) + elif input[i] == '-': + res.append(x - y) + else: + res.append(x * y) + self.dic[input] = res + return res +``` \ No newline at end of file diff --git a/2019.01.04-leetcode279/Ostrichcrab.md b/2019.01.04-leetcode279/Ostrichcrab.md new file mode 100644 index 000000000..16563e006 --- /dev/null +++ b/2019.01.04-leetcode279/Ostrichcrab.md @@ -0,0 +1,17 @@ +``` +class Solution { +public: + int numSquares(int n) { + vector dp; + dp.push_back(0); + for(int i = 1; i <= n; i++) dp.push_back(i); + // for(int i = 0; i <= n; i++) cout< 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 + +**例子** +> **示例 1:** +输入: n = 12 +输出: 3 +解释: 12 = 4 + 4 + 4. + +> **示例 2:** +输入: n = 13 +输出: 2 +解释: 13 = 4 + 9. + +**思想** +**法1**:DP +> 看到 "最小" 之类的词,考虑DP。 + +dp[i] 表示组成和为 i 的完全平方数的最小个数。 +dp[i] = min(dp[i], dp[i-j*j]) + +**法2**:BFS +结点表示剩余的和,边表示完全平方数 + +**解法1** +复杂度 - 时间O(n^2),空间O(n) +```python +class Solution(object): + def numSquares(self, n): + """ + :type n: int + :rtype: int + """ + dp = [i for i in range(n+1)] + for i in range(1, n+1): + for j in range(1, int(i**0.5)+1): + dp[i] = min(dp[i], dp[i-j*j]+1) + return dp[-1] +``` + +**解法2** +BFS +```python +class Solution(object): + def numSquares(self, n): + """ + :type n: int + :rtype: int + """ + depth = 0 + nodes = set([n]) + edges = [i * i for i in range(1, int(n**0.5)+1)] + while edges: + depth += 1 + nextLevel = set() + for node in nodes: + for edge in edges: + if edge == node: + return depth + elif edge < node: + nextLevel.add(node - edge) + else: + break + nodes = nextLevel + return depth +``` + +##### Ref +[Summary of 4 different solutions (BFS, DP, static DP and mathematics)](https://leetcode.com/problems/perfect-squares/discuss/71488/Summary-of-4-different-solutions-(BFS-DP-static-DP-and-mathematics)) \ No newline at end of file diff --git "a/2019.01.04-leetcode279/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2019.01.04-leetcode279/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..1f1360dc0 --- /dev/null +++ "b/2019.01.04-leetcode279/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,16 @@ +``` +class Solution { +public: + int numSquares(int n) { + while (n % 4 == 0) n /= 4; + if (n % 8 == 7) return 4; + for (int a = 0; a * a <= n; ++a) { + int b = sqrt(n - a * a); + if (a * a + b * b == n) { + return !!a + !!b; + } + } + return 3; + } +}; +``` diff --git a/2019.01.05-leetcode127/Ostrichcrab.md b/2019.01.05-leetcode127/Ostrichcrab.md new file mode 100644 index 000000000..5c861956b --- /dev/null +++ b/2019.01.05-leetcode127/Ostrichcrab.md @@ -0,0 +1,36 @@ +``` +public class Solution { + public int ladderLength(String beginWord, String endWord, List wordList) { + + Set wordSet = new HashSet<>(wordList); + Set visited = new HashSet<>(); + visited.add(beginWord); + int dist = 1; + + while (!visited.contains(endWord)) { + Set temp = new HashSet<>(); + for (String word: visited) { + for (int i = 0; i < word.length(); i++) { + char[] chars = word.toCharArray(); + for (int j = (int)'a'; j < (int)'z' + 1; j++) { + chars[i] = (char)j; + String newWord = new String(chars); + if (wordSet.contains(newWord)) { + temp.add(newWord); + wordSet.remove(newWord); + } + } + } + } + dist += 1; + if (temp.size() == 0) { // it nevert get to the endWord + return 0; + } + + visited = temp; + } + + return dist; + } +} +``` diff --git a/2019.01.05-leetcode127/TheRocket.md b/2019.01.05-leetcode127/TheRocket.md new file mode 100644 index 000000000..8665c8aa0 --- /dev/null +++ b/2019.01.05-leetcode127/TheRocket.md @@ -0,0 +1,44 @@ +```java +class Solution { + public int ladderLength(String beginWord, String endWord, List wordList) { + Set dict = new HashSet<>(wordList); + if (!dict.contains(endWord)) { + return 0; + } + Set head = new HashSet<>(); + Set tail = new HashSet<>(); + head.add(beginWord); + tail.add(endWord); + int level = 1; + while (!head.isEmpty() && !tail.isEmpty()) { + ++level; + if (head.size() > tail.size()) { + Set tmp = head; + head = tail; + tail = tmp; + } + Set newHead = new HashSet<>(); + for (String word : head) { + char[] cs = word.toCharArray(); + for (int i = 0; i < cs.length; ++i) { + char ch = cs[i]; + for (char j = 'a'; j <= 'z'; ++j) { + cs[i] = j; + String s = new String(cs); + if (tail.contains(s)) { + return level; + } + if (dict.contains(s)) { + dict.remove(s); + newHead.add(s); + } + } + cs[i] = ch; + } + } + head = newHead; + } + return 0; + } +} +``` diff --git a/2019.01.05-leetcode127/sourcema.md b/2019.01.05-leetcode127/sourcema.md new file mode 100644 index 000000000..fc8cad22c --- /dev/null +++ b/2019.01.05-leetcode127/sourcema.md @@ -0,0 +1,35 @@ +# LeetCode 127 + class Solution { + public int ladderLength(String beginWord, String endWord, List wordList) { + Set set = new HashSet<>(wordList); + if(!set.contains(endWord)){ + return 0; + } + Queue queue=new LinkedList(); + queue.add(beginWord); + int step=1; + while(!queue.isEmpty()){ + int size=queue.size(); + for (int i = 0; i < size; i++) { + String s = queue.poll(); + for (int k = 0; k < s.length(); k++) { + char[] chars = s.toCharArray(); + for (char j = 'a'; j <= 'z'; j++) { + chars[k] = j; + String temp = String.valueOf(chars); + if (set.contains(temp)) { + if (temp.equals(endWord)) { + return step + 1; + } + queue.add(temp); + set.remove(temp); + } + } + } + } + step++; + } + return 0; + + } +} diff --git "a/2019.01.05-leetcode127/\345\215\225\350\257\215\346\216\245\351\276\231" "b/2019.01.05-leetcode127/\345\215\225\350\257\215\346\216\245\351\276\231" new file mode 100644 index 000000000..c9807d2f1 --- /dev/null +++ "b/2019.01.05-leetcode127/\345\215\225\350\257\215\346\216\245\351\276\231" @@ -0,0 +1,32 @@ +给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则: + +每次转换只能改变一个字母。 +转换过程中的中间单词必须是字典中的单词。 +说明: + +如果不存在这样的转换序列,返回 0。 +所有单词具有相同的长度。 +所有单词只由小写字母组成。 +字典中不存在重复的单词。 +你可以假设 beginWord 和 endWord 是非空的,且二者不相同。 +示例 1: + +输入: +beginWord = "hit", +endWord = "cog", +wordList = ["hot","dot","dog","lot","log","cog"] + +输出: 5 + +解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog", + 返回它的长度 5。 +示例 2: + +输入: +beginWord = "hit" +endWord = "cog" +wordList = ["hot","dot","dog","lot","log"] + +输出: 0 + +解释: endWord "cog" 不在字典中,所以无法进行转换。 diff --git "a/2019.01.05-leetcode127/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2019.01.05-leetcode127/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..955681db6 --- /dev/null +++ "b/2019.01.05-leetcode127/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,44 @@ +``` +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + int ret = 0; + + set s(wordList.begin(), wordList.end()); + if(s.find(endWord) == s.end()) + return 0; + + queue q; + q.push(beginWord); + while(!q.empty()) + { + for(int j=q.size(); j>0; j--) + { + string str = q.front(); + q.pop(); + + if(str == endWord) return ret+1; + + for(int i=0; i>& grid, int x0, int y0){ + int n, m, sum=1; + n = grid.size(); + m = grid[0].size(); + + grid[x0][y0] = 0; //当前元素设置为0,避免再次搜索到 + int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}}; + + for(int i=0; i<4; i++){ + int x = x0 + dir[i][0]; + int y = y0 + dir[i][1]; + if(x>=0&&x=0&&y>& grid) + { + int mx = 0, n, m; + n = grid.size(); + m = grid[0].size(); + for(int i=0; i= 0 && grid[i - 1][j] == 1) + sum += dfs(grid, i - 1, j); + if (i + 1 < grid.length && grid[i + 1][j] == 1) + sum += dfs(grid, i + 1, j); + if (j - 1 >= 0 && grid[i][j - 1] == 1) + sum += dfs(grid, i, j - 1); + if (j + 1 < grid[0].length && grid[i][j + 1] == 1) + sum += dfs(grid, i, j + 1); + return sum; + } +} +``` diff --git a/2019.01.06-leetcode695/WYJ.md b/2019.01.06-leetcode695/WYJ.md new file mode 100644 index 000000000..db53f12cd --- /dev/null +++ b/2019.01.06-leetcode695/WYJ.md @@ -0,0 +1,50 @@ +```java +class Solution { + public int maxAreaOfIsland(int[][] grid) { + if(grid.length == 0){ + return 0; + } + boolean[][] judge = new boolean[grid.length][grid[0].length]; + for(int i = 0; i < grid.length; i++){ + for(int j = 0; j < grid[0].length; j++){ + judge[i][j] = false; + } + } + int area = 0; + for(int i = 0; i < grid.length; i++){ + for(int j = 0; j < grid[i].length; j++){ + if(!judge[i][j]&&grid[i][j] == 1){ + area = Math.max(area, findArea(grid, i, j, judge)); + } + } + } + return area; + } + public int findArea(int[][] grid, int x, int y, boolean[][] judge){ + if(grid[x][y] == 0){ + return 0; + } + if(judge[x][y]){ + return 0; + } + else{ + judge[x][y] = true; + int up = 0, down = 0, left = 0, right = 0; + if(x - 1 >= 0){ + up = findArea(grid, x - 1, y, judge); + } + if(x + 1 < grid.length){ + down = findArea(grid, x + 1, y, judge); + } + if(y - 1 >= 0){ + left = findArea(grid, x, y - 1, judge); + } + if(y + 1 < grid[x].length){ + right = findArea(grid, x, y + 1, judge); + } + return 1 + up + down + left + right; + + } + } +} +``` diff --git a/2019.01.06-leetcode695/sourcema.md b/2019.01.06-leetcode695/sourcema.md new file mode 100644 index 000000000..548f1fc10 --- /dev/null +++ b/2019.01.06-leetcode695/sourcema.md @@ -0,0 +1,27 @@ +# LeetCode 695 + class Solution { + public int maxAreaOfIsland(int[][] grid) { + if (grid[0].length == 0 || grid.length == 0) { + return 0; + } + int row=grid.length,col=grid[0].length; + int max=0; + for (int i = 0; i < row; i++) { + for (int j = 0; j < col; j++) { + if (grid[i][j] == 1) { + int count=dfs(grid, i, j); + max = Math.max(max, count); + } + } + } + return max; + } + private int dfs(int[][] grid, int i, int j) { + if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0) { + return 0; + } + grid[i][j]=0; + return 1 + dfs(grid, i - 1, j) + dfs(grid, i + 1, j) + + dfs(grid, i, j - 1) + dfs(grid, i, j + 1); + } +} diff --git "a/2019.01.06-leetcode695/\345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257" "b/2019.01.06-leetcode695/\345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257" new file mode 100644 index 000000000..9af299f60 --- /dev/null +++ "b/2019.01.06-leetcode695/\345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257" @@ -0,0 +1,22 @@ +给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。 + +找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。) + +示例 1: + +[[0,0,1,0,0,0,0,1,0,0,0,0,0], + [0,0,0,0,0,0,0,1,1,1,0,0,0], + [0,1,1,0,1,0,0,0,0,0,0,0,0], + [0,1,0,0,1,1,0,0,1,0,1,0,0], + [0,1,0,0,1,1,0,0,1,1,1,0,0], + [0,0,0,0,0,0,0,0,0,0,1,0,0], + [0,0,0,0,0,0,0,1,1,1,0,0,0], + [0,0,0,0,0,0,0,1,1,0,0,0,0]] +对于上面这个给定矩阵应返回 6。注意答案不应该是11,因为岛屿只能包含水平或垂直的四个方向的‘1’。 + +示例 2: + +[[0,0,0,0,0,0,0,0]] +对于上面这个给定的矩阵, 返回 0。 + +注意: 给定的矩阵grid 的长度和宽度都不超过 50。 diff --git "a/2019.01.06-leetcode695/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" "b/2019.01.06-leetcode695/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" new file mode 100644 index 000000000..248c5105a --- /dev/null +++ "b/2019.01.06-leetcode695/\347\245\236\347\247\230\347\232\204\347\201\253\346\237\264\344\272\272.md" @@ -0,0 +1,26 @@ +``` +class Solution { +public: + vector> dirs{{0,-1},{-1,0},{0,1},{1,0}}; + int maxAreaOfIsland(vector>& grid) { + int m = grid.size(), n = grid[0].size(), res = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] != 1) continue; + int cnt = 0; + helper(grid, i, j, cnt, res); + } + } + return res; + } + void helper(vector>& grid, int i, int j, int& cnt, int& res) { + int m = grid.size(), n = grid[0].size(); + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] <= 0) return; + res = max(res, ++cnt); + grid[i][j] *= -1; + for (auto dir : dirs) { + helper(grid, i + dir[0], j + dir[1], cnt, res); + } + } +}; +``` diff --git a/2019.01.07-leetcode200/TheRocket.md b/2019.01.07-leetcode200/TheRocket.md new file mode 100644 index 000000000..70b08f22b --- /dev/null +++ b/2019.01.07-leetcode200/TheRocket.md @@ -0,0 +1,28 @@ +```java +class Solution { + public int numIslands(char[][] grid) { + int res = 0; + for (int i = 0; i < grid.length; ++i) { + for (int j = 0; j < grid[0].length; ++j) { + if (grid[i][j] == '1') { + ++res; + dfs(grid, i, j); + } + } + } + return res; + } + + private void dfs(char[][] grid, int i, int j) { + grid[i][j] = '0'; + if (i - 1 >= 0 && grid[i - 1][j] == '1') + dfs(grid, i - 1, j); + if (i + 1 = 0 && grid[i][j - 1] == '1') + dfs(grid, i, j - 1); + if (j + 1 < grid[0].length && grid[i][j + 1] == '1') + dfs(grid, i, j + 1); + } +} +``` diff --git a/2019.01.07-leetcode200/marguerite.md b/2019.01.07-leetcode200/marguerite.md new file mode 100644 index 000000000..c9e908cf8 --- /dev/null +++ b/2019.01.07-leetcode200/marguerite.md @@ -0,0 +1,43 @@ +给定的一个二维网格的地图(’1’(陆地)和0(水)),计数岛的数量。岛屿是四面环水,是由相邻的陆地水平或垂直连接而形成的。 + +可以假设该网格的所有四个边都被水包围。采用深度优先遍历,把访问过的改为‘0’,继续遍历 + +``` +public class 岛屿的数量 { + public int numIslands(char[][] grid) { + if (grid == null || grid.length == 0 + || grid[0].length == 0) + return 0; + int rows = grid.length; + int cols = grid[0].length; + int count = 0; + for (int i = 0; i < rows; i++) + for (int j = 0; j < cols; j++) + // 注意char + if (grid[i][j] == '1') { + count++; + dfsSearch(grid, i, j, rows, cols); + } + return count++; + } + + // 每遇到'1'后, 开始向四个方向 递归搜索. 搜到后变为'0', + // 因为相邻的属于一个island. 然后开始继续找下一个'1'. + private void dfsSearch(char[][] grid, + int i, int j, int rows, int cols) { + if (i < 0 || i >= rows || j < 0 || j >= cols) + return; + if (grid[i][j] != '1') + return; + // 也可以才用一个visited数组,标记遍历过的岛屿 + grid[i][j] = '0'; + dfsSearch(grid, i + 1, j, rows, cols); + dfsSearch(grid, i - 1, j, rows, cols); + dfsSearch(grid, i, j + 1, rows, cols); + dfsSearch(grid, i, j - 1, rows, cols); + + } +} + + +``` diff --git a/2019.01.07-leetcode200/sourcema.md b/2019.01.07-leetcode200/sourcema.md new file mode 100644 index 000000000..01bf867af --- /dev/null +++ b/2019.01.07-leetcode200/sourcema.md @@ -0,0 +1,53 @@ +# leetcode 200 + class Solution { + static int count=0; + static int[] parent; + public static int numIslands(char[][] arr) {//并查集解法 + if (arr.length == 0||arr[0].length == 0 ) { + return 0; + } + int length=arr.length * arr[0].length; + int width=arr[0].length; + parent = new int[length]; + for (int i = 0; i < length; i++) { + int x=i/width; + int y=i%width; + if (arr[x][y] - '0' == 1) { + count++; + } + parent[i]=i; + } + for (int i = 0; i < length; i++) {//为什么考查右边和下方 1 0 + int x=i/width; //1 1如果不考察下方,右下角的1就无法抵消啦 + int y=i%width; + int down=x+1; + int right=y+1; + if (right < width && arr[x][y] - '0' == 1 && arr[x][right] - '0' == 1) { + union(i, i+1); + } + if (down < arr.length && arr[x][y] - '0' == 1 && arr[down][y] - '0' == 1) { + union(i, i+width); + } + } + return count; + + } + + public static void union(int p,int q) { + int rootP = find(p); + int rootQ = find(q); + if (rootP == rootQ) { + return; + } + parent[rootQ]=rootP; + count--; + } + + public static int find(int e) { + while (parent[e] != e) { + parent[e] = parent[parent[e]];//让子节点直接连接父节点 + e = parent[e]; + } + return e; + } +} diff --git "a/2019.01.07-leetcode200/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.07-leetcode200/\345\210\230\346\266\246\346\263\275(capture).md" new file mode 100644 index 000000000..ef98406aa --- /dev/null +++ "b/2019.01.07-leetcode200/\345\210\230\346\266\246\346\263\275(capture).md" @@ -0,0 +1,27 @@ +```java + public int numIslands(char[][] grid) { + + int count=0; + for (int i=0;i=0&&y>=0&&y 0) + count++; + return count; + } + + private int dfs(int[][] mat, int i, boolean[] visited) { + if (visited[i]) + return 0; + visited[i] = true; + int count = 1; + for (int j = 0; j < visited.length; j++) + if (i != j && mat[i][j] == 1) + count += dfs(mat, j, visited); + return count; + } + +几次深度优先遍历能遍历所有值为1 的结点,图的连通性。(for 是所有结点,M[i][j]==1这个判断相当于i的邻接点,深度优先遍历) + +public class Solution { + public void dfs(int[][] M, int[] visited, int i) { + for (int j = 0; j < M.length; j++) { + if (M[i][j] == 1 && visited[j] == 0) { + visited[j] = 1; + dfs(M, visited, j); + } + } + } + public int findCircleNum(int[][] M) { + int[] visited = new int[M.length]; + int count = 0; + for (int i = 0; i < M.length; i++) { + if (visited[i] == 0) { + dfs(M, visited, i); + count++; + } + } + return count; + } + +广度优先遍历: +Queue q = new LinkedList<>(); + public void bfs(int[][] M, int[] visited, int i) { + // visit[i]; + q.offer(i); + visited[i] = 1; + while (!q.isEmpty()) { + int node = q.poll(); + for (int j = 0; j < M.length; j++) { + // 未被访问过且是邻接点,注意是node的邻接点 + if (visited[j] == 0 && M[node][j] == 1) { + // visit[j]; + q.offer(j); + visited[j] = 1; + } + } + } + + } + + public int findCircleNum(int[][] M) { + int[] visited = new int[M.length]; + int count = 0; + for (int i = 0; i < M.length; i++) { + if (visited[i] == 0) { + bfs(M, visited, i); + count++; + } + } + return count; + } +``` diff --git a/2019.01.08-leetcode547/sourcema.md b/2019.01.08-leetcode547/sourcema.md new file mode 100644 index 000000000..51f6a5f20 --- /dev/null +++ b/2019.01.08-leetcode547/sourcema.md @@ -0,0 +1,42 @@ +# leetcode 547 + class Solution { + static int[] parent; + static int count; + + public static int findCircleNum(int[][] friends) { + if (friends == null || friends.length == 0 || friends[0].length == 0) { + return 0; + } + parent = new int[friends.length]; + count = friends.length; + for (int i = 0; i < friends.length; i++) { + parent[i] = i; + } + for (int i = 0; i < friends.length; i++) { + for (int j = i+1; j < friends.length; j++) { + if (friends[i][j] == 1) { + union(i, j); + } + } + } + return count; + } + + public static void union(int p, int q) { + int rootP = find(p); + int rootQ = find(q); + if (rootP == rootQ) { + return; + } + parent[rootQ] = rootP; + count--; + } + + public static int find(int e) { + while (parent[e] != e) { + parent[e] = parent[parent[e]];//让子节点直接连接父节点 + e = parent[e]; + } + return e; + } +} diff --git "a/2019.01.08-leetcode547/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.08-leetcode547/\345\210\230\346\266\246\346\263\275(capture).md" new file mode 100644 index 000000000..6d4bddce9 --- /dev/null +++ "b/2019.01.08-leetcode547/\345\210\230\346\266\246\346\263\275(capture).md" @@ -0,0 +1,29 @@ +```java + public int findCircleNum(int[][] M) { + + int circleNum=0; + int[] temp = new int[M.length]; + for (int i : temp){ + temp[i]=0; + } + for (int i=0;i +找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。 +### 1.2 输入与输出 +输入: +* vector< vector< char>>& board:给定二维区域的指针 + +输出: +* void:原地修改 +### 1.3 样例 +#### 1.3.1 样例1 +输入:
+X X X X
+X O O X
+X X O X
+X O X X
+输出:
+X X X X
+X X X X
+X X X X
+X O X X
+解释:
+被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O'
最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。 + +## 2 思路描述与代码 +### 2.1 思路描述(DFS) +1. DFS编辑边界中的 'O',将边界以及与边界的 'O' 相连的 'O' 标记为 '*'; +2. 然后遍历区域,若区域的值为 '*' ,则更新为 'O',若区域的值为 O' 则更新为 'X'。 + +比如输入:
+X X X X
+X O O X
+X X O X
+X O X X
+ +经过步骤1处理后为
+X X X X
+X O O X
+X X O X
+X * X X
+ +经过步骤2处理后为
+X X X X
+X X X X
+X X X X
+X O X X
+ +### 2.2 代码 +```cpp +//函数中涉及到的c++知识 +//vector> board 是个长度、宽度可变的二维 char 数组,c++里面称为容器 +//board.size() 可以获取行数, board[0].size() 可以获取列数 +void solve(vector>& board) { + int row = board.size(); + if(row == 0) return ; + int col = board[0].size(); + if(col == 0) return ; + //上下边界DFS + for( int j = 0; j < col; j++ ){ + DFS(board, 0, j); + DFS(board, row-1, j); + } + //左右边界DFS + for( int i = 1; i < row - 1; i++ ){ + DFS(board, i, 0); + DFS(board, i, col-1); + } + //根据遍历结果重新更新结果 + //如果是 '*' 则说明该点与边界的 'O' 相连,于是需要更新为 'O' + //如果是 'O' 则说明该点不与边界的 'O' 相连,于是需要更新为 'X' + for( int i = 0; i < row; i++ ){ + for( int j = 0; j < col; j++ ){ + if(board[i][j] == 'O') board[i][j] = 'X'; + else if(board[i][j] == '*') board[i][j] = 'O'; + } + } + +} +void DFS(vector>& board, int i, int j){ + //越界或者不是与边界0相连的0则返回 + if(i < 0 || i >= board.size() || j < 0 || j >= board[0].size() || board[i][j] != 'O') return ; + //其他情况就是与边界0相连的0,然后标记为'*' + board[i][j] = '*'; + DFS(board, i - 1, j); + DFS(board, i + 1, j); + DFS(board, i , j - 1); + DFS(board, i , j + 1); +} +``` +## 3 思考与拓展 +### 3.1 思考 +本题有两个思路,一个是求内部与边界0的连通区域,另外一个是上述描述。一个从内而外,一个从外到内,值得注意的是从外而内思路更清晰,代码也更容易书写。 +#### 3.1.1 其他方法 +无。 +#### 3.1.2 复杂度分析 +方法|空间复杂度|时间复杂度 +--- | --- | --- +DFS|O(mn)|O(mn) +#### 3.1.3 难点分析 +1. 选定由内而外还是由外而内的思路; +2. 选用DFS还是BFS + +### 3.2 拓展 +可以尝试使用BFS解决该题。 diff --git a/2019.01.09-leetcode130/Ostrichcrab.md b/2019.01.09-leetcode130/Ostrichcrab.md new file mode 100644 index 000000000..8fbadcabe --- /dev/null +++ b/2019.01.09-leetcode130/Ostrichcrab.md @@ -0,0 +1,67 @@ +``` +class Solution { +public: + int n,m; + int dx[4]={0,0,1,-1}; + int dy[4]={1,-1,0,0}; + vector >flag; + + void bfs(vector >& board,int x,int y){ + queue >q; + q.push(make_pair(x,y)); + flag[x][y]=1; + + while(!q.empty()){ + int qx=q.front().first; + int qy=q.front().second; + q.pop(); + for(int i=0;i<4;i++){ + int tx=qx+dx[i]; + int ty=qy+dy[i]; + if(tx>=0&&tx=0&&ty >& board) { + if(board.empty()){ + return ; + } + n=board.size(); + m=board[0].size(); + flag.resize(n); + for(int i=0;i= board.length || j < 0 || j >= board[0].length || board[i][j] != 'O') { + return; + } + board[i][j] = '1'; + dfs(board, i - 1, j); + dfs(board, i + 1, j); + dfs(board, i, j - 1); + dfs(board, i, j + 1); + } +} +``` diff --git "a/2019.01.09-leetcode130/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.09-leetcode130/\345\210\230\346\266\246\346\263\275(capture).md" new file mode 100644 index 000000000..d6a52d766 --- /dev/null +++ "b/2019.01.09-leetcode130/\345\210\230\346\266\246\346\263\275(capture).md" @@ -0,0 +1,47 @@ +```java + public void solve(char[][] board) { + + if (board.length==0) return; + + for (int i=0;i=0&&x=0&&y1){ + check(board, i-1, j, row, col); + } + if(j>1){ + check(board, i, j-1, row, col); + } + if(i+1> res; + vector> visited; + void dfs(vector>& matrix, int x, int y, int pre, int preval){ + if(x<0 || x>=matrix.size() || y<0 || y>=matrix[0].size() || + matrix[x][y]
> pacificAtlantic(vector>& matrix) {
+        if(matrix.empty()) return res;
+        int m = matrix.size(), n = matrix[0].size();
+        visited.resize(m,vector(n,0));
+        for(int i = 0; i < m; i++){
+            dfs(matrix,i,0,INT_MIN,1);
+            dfs(matrix,i,n-1,INT_MIN,2);
+        }
+        for(int i = 0; i < n; i++){
+            dfs(matrix,0,i,INT_MIN,1);
+            dfs(matrix,m-1,i,INT_MIN,2);
+        }
+        return res;
+    }
+};
+```
diff --git a/2019.01.10-leetcode417/TheRocket.md b/2019.01.10-leetcode417/TheRocket.md
new file mode 100644
index 000000000..0edad38ba
--- /dev/null
+++ b/2019.01.10-leetcode417/TheRocket.md
@@ -0,0 +1,49 @@
+```java
+class Solution {
+    public List pacificAtlantic(int[][] matrix) {
+        List res = new ArrayList<>();
+        if (matrix == null || matrix.length == 0) {
+            return res;
+        }
+        int m = matrix.length;
+        int n = matrix[0].length;
+        boolean[][] fromPacific = new boolean[m][n];
+        boolean[][] fromAtlantic  = new boolean[m][n];
+        for (int i = 0; i < m; ++i) {
+            dfs(matrix, fromPacific, i, 0);
+            dfs(matrix, fromAtlantic, i, n - 1);
+        }
+        for (int i = 0; i < n; ++i) {
+            dfs(matrix, fromPacific, 0, i);
+            dfs(matrix, fromAtlantic, m - 1, i);
+        }
+        for (int i = 0; i < m; ++i) {
+            for (int j = 0; j < n; ++j) {
+                if (fromPacific[i][j] && fromAtlantic[i][j]) {
+                    res.add(new int[] {i, j});
+                }
+            }
+        }
+        return res;
+    }
+
+    private void dfs(int[][] matrix, boolean[][] fromOcean, int i, int j) {
+        if (fromOcean[i][j]) {
+            return;
+        }
+        fromOcean[i][j] = true;
+        if (i - 1 >= 0 && matrix[i - 1][j] >= matrix[i][j]) {
+            dfs(matrix, fromOcean, i - 1, j);
+        }
+        if (i + 1 < matrix.length && matrix[i + 1][j] >= matrix[i][j]) {
+            dfs(matrix, fromOcean, i + 1, j);
+        }
+        if (j - 1 >= 0 && matrix[i][j - 1] >= matrix[i][j]) {
+            dfs(matrix, fromOcean, i, j - 1);
+        }
+        if (j + 1 < matrix[0].length && matrix[i][j + 1] >= matrix[i][j]) {
+            dfs(matrix, fromOcean, i, j + 1);
+        }
+    }
+}
+```
diff --git a/2019.01.10-leetcode417/marguerite.md b/2019.01.10-leetcode417/marguerite.md
new file mode 100644
index 000000000..49129b347
--- /dev/null
+++ b/2019.01.10-leetcode417/marguerite.md
@@ -0,0 +1,68 @@
+给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。“太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。
+
+规定水流只能按照上、下、左、右四个方向流动,且只能从高到低或者在同等高度上流动。
+
+请找出那些水流既可以流动到“太平洋”,又能流动到“大西洋”的陆地单元的坐标。
+提示:
+输出坐标的顺序不重要
+m 和 n 都小于150
+ 
+示例:
+给定下面的 5x5 矩阵:
+
+  太平洋 ~   ~   ~   ~   ~ 
+       ~  1   2   2   3  (5) *
+       ~  3   2   3  (4) (4) *
+       ~  2   4  (5)  3   1  *
+       ~ (6) (7)  1   4   5  *
+       ~ (5)  1   1   2   4  *
+          *   *   *   *   * 大西洋
+
+返回:
+
+[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (上图中带括号的单元).
+
+##题目思路很明确,用两个数组来记录哪些点可以去大西洋,
+##哪些可以去太平洋,然后将又能去大西洋,又能去太平洋的点输出。判断哪些点能去的思路用启发式的方式递归做。
+
+```
+public class Solution {
+    public List pacificAtlantic(int[][] matrix) {
+ 
+        List results = new ArrayList();
+        int m = matrix.length;
+        if(m == 0) return results;
+        int n = matrix[0].length;
+        int[][] toAtlantic = new int[m][n];
+        int[][] toPacific = new int[m][n];
+ 
+        for(int i = 0; i< m; i ++){
+            toAtlantic[i][n-1] = 1;
+            toPacific[i][0] = 1;
+            reactiveCell(matrix,toAtlantic,i,n-1,m,n);
+            reactiveCell(matrix,toPacific,i,0,m,n);
+        }
+        for(int i = 0; i < n; i ++){
+            toAtlantic[m-1][i] = 1;
+            toPacific[0][i] = 1;
+            reactiveCell(matrix,toAtlantic,m-1,i,m,n);
+            reactiveCell(matrix,toPacific,0,i,m,n);
+        }
+ 
+        for(int i = 0; i < m; i ++)
+            for(int j = 0 ; j < n ; j ++){
+                if(toAtlantic[i][j] == 1 && toPacific[i][j] == 1){ int[]result = new int[]{i,j}; results.add(result);}
+            }
+        return  results;
+    }
+ 
+    public void reactiveCell(int[][] matrix,int[][] markMatrix,int i,int j,int m,int n){
+ 
+        if( i > 0 && matrix[i-1][j] >= matrix[i][j] && markMatrix[i-1][j] == 0) {markMatrix[i-1][j] = 1;reactiveCell(matrix,markMatrix,i-1,j,m,n);}
+        if( i < m-1 && matrix[i+1][j] >= matrix[i][j] && markMatrix[i+1][j] == 0) {markMatrix[i+1][j] = 1;reactiveCell(matrix,markMatrix,i+1,j,m,n);}
+        if( j > 0 && matrix[i][j-1] >= matrix[i][j] && markMatrix[i][j-1] == 0) {markMatrix[i][j-1] = 1; reactiveCell(matrix,markMatrix,i,j-1,m,n);}
+        if( j < n-1 && matrix[i][j+1] >= matrix[i][j] && markMatrix[i][j+1] == 0) {markMatrix[i][j+1] = 1;reactiveCell(matrix,markMatrix,i,j+1,m,n);}
+    }
+}
+
+```
diff --git a/2019.01.10-leetcode417/sourcema.md b/2019.01.10-leetcode417/sourcema.md
new file mode 100644
index 000000000..d30c27a59
--- /dev/null
+++ b/2019.01.10-leetcode417/sourcema.md
@@ -0,0 +1,44 @@
+# leetcode 417
+    class Solution {
+    private static int[][] d = {{0,1}, {1,0}, {0,-1}, {-1,0}};
+    private static int row;
+    private static int col;
+    public static List pacificAtlantic(int[][] matrix) {
+        List res = new ArrayList<>();
+        if (matrix == null || matrix.length == 0) {
+            return res;
+        }
+        row=matrix.length;
+        col=matrix[0].length;
+        boolean[][] pacific = new boolean[row][col];
+        boolean[][] atlantic = new boolean[row][col];
+        for (int i = 0; i = 0 && nextX < row && nextY >= 0 && nextY < col && !arr[nextX][nextY]
+                    && matrix[nextX][nextY] >= matrix[x][y]) {
+                dfs(matrix,arr,nextX,nextY);
+            }
+        }
+    }
+}
diff --git "a/2019.01.10-leetcode417/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.10-leetcode417/\345\210\230\346\266\246\346\263\275(capture).md"
new file mode 100644
index 000000000..8444a8b67
--- /dev/null
+++ "b/2019.01.10-leetcode417/\345\210\230\346\266\246\346\263\275(capture).md"
@@ -0,0 +1,48 @@
+```java
+  public List pacificAtlantic(int[][] matrix) {
+        
+        List res = new ArrayList<>();
+        boolean[] booleans = new boolean[]{false,false};
+        if (matrix.length==0)return res;
+        int[][] matrixDemo = new int[matrix.length][matrix[0].length];
+        for (int i=0;i 0 && matrix[y][x] >= matrix[y][x - 1]) findArea(x - 1, y, matrix, booleans, matrixDemo);
+            if (x < matrix[0].length - 1 && matrix[y][x] >= matrix[y][x + 1]) findArea(x + 1, y, matrix, booleans, matrixDemo);
+            if (y > 0 && matrix[y][x] >= matrix[y - 1][x]) findArea(x, y - 1, matrix, booleans, matrixDemo);
+            if (y < matrix.length - 1 && matrix[y][x] >= matrix[y + 1][x]) findArea(x, y + 1, matrix, booleans, matrixDemo);
+        }
+    }
+
+    public void clear(int[][] matrixDemo){
+        for (int i=0;i pacificAtlantic(int[][] matrix) {
+        List res = new LinkedList<>();
+		
+		if(null==matrix||matrix.length==0||matrix[0].length==0){
+			return res;
+		}
+		
+		int row = matrix.length;
+		int col = matrix[0].length;
+		boolean[][] pacific = new boolean[row][col];
+		boolean[][] atlantic = new boolean[row][col];
+		
+		//遍历竖着的左右两列
+		for(int i=0;i=n||y<0||y>=m||visited[x][y]==true||matrix[x][y] letterCombinations(string digits) {
+        
+        vector res;
+        if(digits.size()==0)return res;
+        string list[]={"","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
+        res.push_back("");
+        for(int i=0;i letterCombinations(String digits) {
+        List res = new ArrayList<>();
+        if (digits == null || digits.length() == 0) {
+            return res;
+        }
+        res.add("");
+        String[] dict = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
+        for (char c : digits.toCharArray()) {
+            List tmp = new ArrayList<>();
+            String s = dict[c - '2'];
+            for (String prefix : res) {
+                for (char cur : s.toCharArray()) {
+                    tmp.add(prefix + cur);
+                }
+            }
+            res = tmp;
+        }
+        return res;
+    }
+}
+```
diff --git a/2019.01.11-leetcode17/WYJ.md b/2019.01.11-leetcode17/WYJ.md
new file mode 100644
index 000000000..6b50fc7d2
--- /dev/null
+++ b/2019.01.11-leetcode17/WYJ.md
@@ -0,0 +1,25 @@
+```java
+class Solution {
+    private List res = new ArrayList<>();
+    public List letterCombinations(String digits) {
+        if(digits.length() == 0){
+            return res;
+        }
+        String[] dic = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
+        dfs(digits, 0, "", dic);
+        return res;
+        
+    }
+    private void dfs(String digits, int index, String s, String[] dic){
+        if(index == digits.length()){
+            res.add(s);
+            return;
+        }
+        int num = digits.charAt(index) - '0';
+        for(int i = 0; i < dic[num].length(); i++){
+            dfs(digits, index + 1, s + String.valueOf(dic[num].charAt(i)), dic);
+        }
+        return;
+    }
+}
+```
diff --git a/2019.01.11-leetcode17/sourcema.md b/2019.01.11-leetcode17/sourcema.md
new file mode 100644
index 000000000..7bad697a6
--- /dev/null
+++ b/2019.01.11-leetcode17/sourcema.md
@@ -0,0 +1,26 @@
+# leetcode 17
+    class Solution {
+    
+    static String[] letters = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
+    public static List letterCombinations(String digits) {
+        List res = new ArrayList<>();
+        if (digits == null || digits.length() == 0) {
+            return res;
+        }
+        dfs(digits, res, 0, digits.length(), "");
+        return res;
+    }
+
+    private static void dfs(String digits, List res, int index, int length, String ret) {
+        if (index >= length) {
+            res.add(ret);
+            return;
+        }
+        int digit = digits.charAt(index) - '0';
+        for (int i = 0; i  letterCombinations(String digits) {
+        List res =  new ArrayList();
+        if (digits.length()==0) return res;
+        Map map = new HashMap<>();
+        map.put("2",new String[]{"a","b","c"});
+        map.put("3",new String[]{"d","e","f"});
+        map.put("4",new String[]{"g","h","i"});
+        map.put("5",new String[]{"j","k","l"});
+        map.put("6",new String[]{"m","n","o"});
+        map.put("7",new String[]{"p","q","r","s"});
+        map.put("8",new String[]{"t","u","v"});
+        map.put("9",new String[]{"w","x","y","z"});
+
+        List list = new ArrayList<>();
+        for (int i=0;i list, int depth, int width, List res, String tempStr){
+        for (int i=0;i letterCombinations(String digits) {
+		LinkedList res = new LinkedList<>();
+        if(digits.isEmpty()){
+        	return res;
+        }
+        String[]  mapping = {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
+        res.add("");
+        
+        for(int i=0;i restoreIpAddresses(string s) {
+        vector res;
+        findIp(s, 0, 0, "", res);
+        return res;
+    }
+    void findIp(string s, int f, int idx, string ip, vector &res){
+        if(idx == 3){
+            if(s.size() - 1 - f < 3){
+                if(s[f] == '0' && f != s.size() - 1) return;
+                int num = stoi(s.substr(f, s.size() - f)); 
+                if(num < 256){
+                    ip += to_string(num);
+                    res.push_back(ip);
+                }
+            }
+        }
+        else{
+            for(int i = 1; i <= 3; i++){
+                if(f + i >= s.size()) break;
+                int num = stoi(s.substr(f, i));
+                if(num < 256)
+                    findIp(s, f + i, idx + 1, ip + to_string(num) + ".", res);
+                if(s[f] == '0' && i == 1) break;
+            }
+        }
+    }
+};
+```
diff --git a/2019.01.12-leetcode93/TheRocket.md b/2019.01.12-leetcode93/TheRocket.md
new file mode 100644
index 000000000..cd3d5260d
--- /dev/null
+++ b/2019.01.12-leetcode93/TheRocket.md
@@ -0,0 +1,38 @@
+```java
+class Solution {
+    public List restoreIpAddresses(String s) {
+        List res = new ArrayList<>();
+        if (s == null || s.length() < 4) {
+            return res;
+        }
+        dfs(s, res, new StringBuilder(), 0, 0);
+        return res;
+    }
+
+    private void dfs(String s, List res, StringBuilder ip, int index, int cnt) {
+        if (cnt > 4) {
+            return;
+        }
+        if (cnt == 4 && index == s.length()) {
+            res.add(ip.toString());
+            return;
+        }
+        for (int i = 1; i < 4; ++i) {
+            int end = index + i;
+            if (end > s.length()) {
+                break;
+            }
+            String sub = s.substring(index, end);
+            if ((sub.startsWith("0") && sub.length() > 1) || Integer.parseInt(sub) > 255) {
+                break;
+            }
+            if (cnt < 3) {
+                sub += ".";
+            }
+            ip.append(sub);
+            dfs(s, res, ip, end, cnt + 1);
+            ip.delete(ip.length() - sub.length(), ip.length());
+        }
+    }
+}
+```
diff --git a/2019.01.12-leetcode93/WYJ.md b/2019.01.12-leetcode93/WYJ.md
new file mode 100644
index 000000000..639ea6e15
--- /dev/null
+++ b/2019.01.12-leetcode93/WYJ.md
@@ -0,0 +1,29 @@
+```java
+class Solution {
+    private List res = new ArrayList<>();
+    public List restoreIpAddresses(String s) {
+        dfs(s, 0, "", 0);
+        return res;
+    }
+    private void dfs(String s, int index, String ip, int splitNum){
+        if(splitNum == 4){
+            if(index >= s.length()){
+                res.add(ip.substring(0, ip.length() - 1)); 
+            }
+            return;
+        }
+        for(int i = 1; i < 4&&index + i <= s.length(); i++){
+            String temp = s.substring(index, index + i);
+            if(temp.length() >1&&temp.charAt(0) == '0'){
+                return;
+            }
+            int num = Integer.valueOf(temp);
+            if(num > 255|| num < 0){
+                return;
+            }
+            dfs(s, index + i, ip + temp + ".", splitNum + 1);
+        }
+        return;
+    }
+}
+```
diff --git a/2019.01.12-leetcode93/marguerite.md b/2019.01.12-leetcode93/marguerite.md
new file mode 100644
index 000000000..1f617455c
--- /dev/null
+++ b/2019.01.12-leetcode93/marguerite.md
@@ -0,0 +1,90 @@
+给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
+
+示例:
+
+输入: "25525511135"
+输出: ["255.255.11.135", "255.255.111.35"]
+
+##这道题的主要思路是分治,将问题的规模不断缩小。回溯中好多的题目都是使用这个思想来解题的。
+
+IP地址被三个”.”分割成了4个部分,这里我把每一个部分叫做一个段,依次为第0段,第1段,第2段,第3段。
+
+那么给定一个只包含数字的字符串,如果求出有效的ip地址呢? 
+以25525511135为例来分析。考虑第0段可能的取值,由于每一个段可以包含1位,2位或3位,那么第0段可能的取值是: 
+2 
+25 
+255
+
+##第0段取值以后后面的字符串需要被分割成3段,那么后面的字符能否被分割成3段呢? 
+
+##第0段取上面的值后,剩余的部分依次为: 
+
+##5525511135 ,字符串的长度为10,而3段最长也只能为9,所以第0段取2时没有对应的有效ip地址。 
+
+##525511135 ,这里字符串的长度为9,即这个字符串还可能被分割成有效的3段。 
+
+##25511135 ,这里字符串的长度为8,即这个字符串还可能被分割成有效的3段。 
+
+##然后再对525511135和25511135求分割成3段的方法。这里问题规模就缩小了。需要被分割的段由4段变成了3了,字符串的长度也变短了。
+
+##递归退出的条件是遍历到字符串尾端并且字符串被分割成了4段。
+
+还需要注意的是:
+
+##如果一个段包含3个字符,那么这三个字符不能大于”255”,这是ip地址的基本知识;
+
+##如果一个字符包括2个或3个字符,它的第一个字符不能为0。
+
+```
+class Solution {
+public:
+    vector restoreIpAddresses(string s) {
+        vector result;
+        string path;
+        helper(s,0,0,path,result);
+        return result;
+    }
+
+    void helper(string &s,int num,int pos,string &path,vector& result)
+    {
+        //遍历完给定字符串,并且生成了个段时
+        if(pos==s.size()&&num==4)
+        {
+            //这里需要去除掉path最后的.
+            result.push_back(path.substr(0,path.size()-1));
+            return;
+        }
+
+        //如果该段包含的字符数大于规定的最大数目,那么直接退出,可以把这个判断放在下面的if中,
+        //但是三个if都需要加,所以放在这儿更简洁一些。
+        if(s.size()-pos>3*(4-num))
+            return;
+
+        //该段只含有一个字符
+        if(pos restoreIpAddresses(String s) {
+        List res = new ArrayList<>();
+        if (s == null || s.length() == 0||s.length()<4||s.length()>12) {
+            return res;
+        }
+        dfs(s, res, 0, "");
+        return res;
+    }
+
+    private static void dfs(String ip, List res, int index, String ret) {
+        if (index == 3) {
+           if ((ip.length()==1||(ip.length()>1&&ip.length()<4&&ip.charAt(0)!='0'))
+                    &&Integer.valueOf(ip) <= 255) {//Integer.valueOf(ip)防止ip的位数超出int范围 首位不能以0开头
+                res.add(ret+ip);
+            }
+            return;
+        }
+        for (int i = 1; i < 4; i++) {
+            String split = ip.substring(0, i>ip.length()?ip.length():i);//可能出现ip的长度小于i的情况,不够长度去切分
+            if ((split.length()==1||(split.length()>1&&split.charAt(0)!='0'))
+                    &&Integer.valueOf(split) <= 255) {
+                ret = ret + split + ".";
+                dfs(ip.substring(i>ip.length()?ip.length():i),res,index+1,ret);
+                ret = ret.substring(0,ret.length() - split.length() - 1);
+            }
+        }
+    }
+}
diff --git "a/2019.01.12-leetcode93/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.12-leetcode93/\345\210\230\346\266\246\346\263\275(capture).md"
new file mode 100644
index 000000000..06aa4541b
--- /dev/null
+++ "b/2019.01.12-leetcode93/\345\210\230\346\266\246\346\263\275(capture).md"
@@ -0,0 +1,31 @@
+```java
+    public List restoreIpAddresses(String s) {
+
+        List res = new ArrayList<>();
+        if (s.length()<4||s.length()>12) return res;
+        getRes(s,4,"",res);
+        return res;
+    }
+
+    public void getRes(String currStr, int rdeep, String currResStr, List res){
+        if (currStr.length()rdeep*3) return;
+        if (rdeep==1){
+            if (currStr.length()>1&&currStr.startsWith("0")) return;//排除长度大于1且开头为0的情况
+            if (currStr.length()==3&&Integer.valueOf(currStr)>255) return;//排除长度为3且大于255的情况
+            res.add(currResStr+"."+currStr);
+            return;
+        }
+        for (int i=1;i<4;i++){
+            if (i>=currStr.length()) break;
+            if (i>1&&currStr.startsWith("0")) break; //排除长度大于1且开头为0的情况
+            if (i!=3||Integer.valueOf(currStr.substring(0,i))<=255) {  //排除长度为3且大于255的情况
+                if (currResStr.equals("")) {
+                    getRes(currStr.substring(i),rdeep-1,currStr.substring(0,i),res);
+                }else{
+                    getRes(currStr.substring(i),rdeep-1,currResStr+"."+currStr.substring(0,i),res);
+                }
+
+            }
+        }
+    }
+```
diff --git "a/2019.01.12-leetcode93/\345\244\215\345\216\237IP\345\234\260\345\235\200" "b/2019.01.12-leetcode93/\345\244\215\345\216\237IP\345\234\260\345\235\200"
new file mode 100644
index 000000000..0d9fb59d5
--- /dev/null
+++ "b/2019.01.12-leetcode93/\345\244\215\345\216\237IP\345\234\260\345\235\200"
@@ -0,0 +1,6 @@
+给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
+
+示例:
+
+输入: "25525511135"
+输出: ["255.255.11.135", "255.255.111.35"]
diff --git "a/2019.01.12-leetcode93/\346\243\225\346\246\210\346\240\221.md" "b/2019.01.12-leetcode93/\346\243\225\346\246\210\346\240\221.md"
new file mode 100644
index 000000000..8fb22b4ce
--- /dev/null
+++ "b/2019.01.12-leetcode93/\346\243\225\346\246\210\346\240\221.md"
@@ -0,0 +1,30 @@
+```
+class Solution {
+    public List restoreIpAddresses(String s) {
+         List res = new LinkedList();
+        if(s.length()==0||null==s){
+        	return res;
+        }
+        dfs(s, res, "", 0, 0);
+        return res;
+    }
+    
+     public void dfs(String s,List res,String ip,int idx,int count){
+    	if(count>4) return;
+    	if(count==4&&s.length()==idx){
+    		res.add(ip);
+    		return;
+    	}
+    	
+    	for(int i=1;i<4;i++){
+    		//s.length()-idx > (4-count)*3
+    		if(idx+i>s.length()) break;
+    		String sub = s.substring(idx, idx+i);
+    		if(sub.startsWith("0")&&sub.length()>1||Integer.parseInt(sub)>=256) break;
+    		dfs(s, res, ip+sub+(count==3?"":"."), idx+i, count+1);
+    	}
+    	
+    }
+}
+
+```
diff --git a/2019.01.13-leetcode79/Ostrichcrab.md b/2019.01.13-leetcode79/Ostrichcrab.md
new file mode 100644
index 000000000..503b5d84f
--- /dev/null
+++ b/2019.01.13-leetcode79/Ostrichcrab.md
@@ -0,0 +1,30 @@
+```
+class Solution {
+public:
+    bool dfs(vector>& board, string word,int x, int y, int len)
+    {
+        if(len == word.length()) return true;
+        if(x<0||y<0||x>=board.size()||y>=board[0].size()||board[x][y]!=word[len]) 
+            return false;
+        board[x][y]^=128;
+        bool res = dfs(board,word,x-1,y,len+1)||
+                   dfs(board,word,x+1,y,len+1)||
+                   dfs(board,word,x,y+1,len+1)||
+                   dfs(board,word,x,y-1,len+1) ;
+        board[x][y]^=128;
+        return res;
+    }
+    bool exist(vector>& board, string word) {
+        int n = board.size();
+        int m = board[0].size();
+        for(int i = 0; i < n; i++)
+        {
+            for(int j = 0; j < m; j++)
+            {
+                if(dfs(board,word,i,j,0)) return true;
+            }
+        }
+        return false;
+    }
+};
+```
diff --git a/2019.01.13-leetcode79/TheRocket.md b/2019.01.13-leetcode79/TheRocket.md
new file mode 100644
index 000000000..73b66409b
--- /dev/null
+++ b/2019.01.13-leetcode79/TheRocket.md
@@ -0,0 +1,30 @@
+```java
+class Solution {
+    public boolean exist(char[][] board, String word) {
+        for (int i = 0; i < board.length; ++i) {
+            for (int j = 0; j < board[0].length; ++j) {
+                if (dfs(board, i, j, word, 0)) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    private boolean dfs(char[][] board, int i, int j, String word, int index) {
+        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(index)) {
+            return false;
+        }
+        if (index == word.length() - 1) {
+            return true;
+        }
+        board[i][j] ^= 128;
+        boolean flag = dfs(board, i - 1, j, word, index + 1) ||
+                dfs(board, i + 1, j, word, index + 1) ||
+                dfs(board, i, j - 1, word, index + 1) ||
+                dfs(board, i, j + 1, word, index + 1);
+        board[i][j] ^= 128;
+        return flag;
+    }
+}
+```
diff --git a/2019.01.13-leetcode79/WYJ.md b/2019.01.13-leetcode79/WYJ.md
new file mode 100644
index 000000000..5d996ac5b
--- /dev/null
+++ b/2019.01.13-leetcode79/WYJ.md
@@ -0,0 +1,38 @@
+```java
+class Solution {
+    private boolean[][] used;
+    public boolean exist(char[][] board, String word) {
+        if(word.length() == 0 || board.length == 0 ||board[0].length == 0){
+            return false;
+        }
+        used = new boolean[board.length][board[0].length];
+        for(int i = 0; i < board.length; i++){
+            for(int j = 0; j < board[0].length; j++){
+                dfs(board, word, 0, i, j);
+            }
+        }
+        return res.size() != 0;
+    }
+    private boolean dfs(char[][] board, String word, int index, int i, int j){
+        if(index == word.length()){
+            return true;
+        }
+        if(i < 0||i >= board.length||j < 0||j >= board[0].length||used[i][j]){
+            return false;
+        }
+        if(index < word.length()&&board[i][j]!=word.charAt(index)){
+            return false;
+        }
+
+        used[i][j] = true;
+        if(dfs(board, word, index + 1, i - 1, j)
+            ||dfs(board, word, index + 1, i + 1, j)
+            ||dfs(board, word, index + 1, i, j - 1)
+            ||dfs(board, word, index + 1, i, j + 1)){
+            return true;
+        }
+        used[i][j] = false;
+        return false;
+    } 
+}
+```
diff --git a/2019.01.13-leetcode79/sourcema.md b/2019.01.13-leetcode79/sourcema.md
new file mode 100644
index 000000000..8996c93c5
--- /dev/null
+++ b/2019.01.13-leetcode79/sourcema.md
@@ -0,0 +1,33 @@
+# leetcode 79
+    class Solution {
+    public boolean exist(char[][] board, String word) {
+        if (board[0].length == 0 || board.length == 0) {
+            return false;
+        }
+        int row=board.length,col=board[0].length,count=0;
+        boolean flag=false;
+        go:
+        for (int i = 0; i < row; i++) {
+            for (int j = 0; j < col; j++) {
+                flag=dfs(board,word,i,j,count);
+                if (flag) {
+                    break go;
+                }
+            }
+        }
+        return flag;
+    }
+    private  boolean dfs(char[][] board, String word,int i, int j, int count) {
+        if (count == word.length()) {
+            return true;
+        }
+        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || word.charAt(count) != board[i][j]) {
+            return false;
+        }
+        board[i][j]^=256;
+        boolean flag=dfs(board,word,i+1,j,count+1)||dfs(board,word,i-1,j,count+1)
+                ||dfs(board,word,i,j+1,count+1)||dfs(board,word,i,j-1,count+1);
+        board[i][j]^=256;
+        return flag;
+    }
+}
diff --git "a/2019.01.13-leetcode79/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.13-leetcode79/\345\210\230\346\266\246\346\263\275(capture).md"
new file mode 100644
index 000000000..6705fb5e2
--- /dev/null
+++ "b/2019.01.13-leetcode79/\345\210\230\346\266\246\346\263\275(capture).md"
@@ -0,0 +1,39 @@
+```java
+  public boolean exist(char[][] board, String word) {
+
+        if (board.length==0) return false;
+        int[][] boardBak = new int[board.length][board[0].length];
+
+        char[] chars = word.toCharArray();
+        for (int i=0;i=board.length||j<0||j>=board[0].length) return false;
+        if (boardBak[i][j]==1) return false;
+        boolean up=false,down=false,left=false,right=false;
+
+        if (board[i][j]==chars[deep]){
+            boardBak[i][j]=1;
+            if (chars.length==deep+1) {
+                return true;
+            }
+            up=(deepsearch(i-1,j,board,boardBak,chars,deep+1));
+            if (!up) down=deepsearch(i+1,j,board,boardBak,chars,deep+1);
+            if (!(up||down))left=deepsearch(i,j-1,board,boardBak,chars,deep+1);
+            if (!(up||down||left))right=deepsearch(i,j+1,board,boardBak,chars,deep+1);
+        }
+        if (up||down||left||right) {
+            return true;
+        }else {
+            boardBak[i][j]=0;
+            return false;
+        }
+    }
+```
diff --git "a/2019.01.13-leetcode79/\345\215\225\350\257\215\346\220\234\347\264\242" "b/2019.01.13-leetcode79/\345\215\225\350\257\215\346\220\234\347\264\242"
new file mode 100644
index 000000000..6f66c0f1e
--- /dev/null
+++ "b/2019.01.13-leetcode79/\345\215\225\350\257\215\346\220\234\347\264\242"
@@ -0,0 +1,16 @@
+给定一个二维网格和一个单词,找出该单词是否存在于网格中。
+
+单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
+
+示例:
+
+board =
+[
+  ['A','B','C','E'],
+  ['S','F','C','S'],
+  ['A','D','E','E']
+]
+
+给定 word = "ABCCED", 返回 true.
+给定 word = "SEE", 返回 true.
+给定 word = "ABCB", 返回 false.
diff --git "a/2019.01.13-leetcode79/\346\243\225\346\246\210\346\240\221.md" "b/2019.01.13-leetcode79/\346\243\225\346\246\210\346\240\221.md"
new file mode 100644
index 000000000..fcd92bad9
--- /dev/null
+++ "b/2019.01.13-leetcode79/\346\243\225\346\246\210\346\240\221.md"
@@ -0,0 +1,35 @@
+```
+class Solution {
+    public boolean exist(char[][] board, String word) {
+		if (word.length()==0||word.isEmpty()) {
+			return true;
+		}
+
+		for (int i = 0; i < board.length; i++) {
+			for (int j = 0; j < board[0].length; j++) {
+				if(dfs(board, word, 0, i, j)){
+					return true;
+				}
+			}
+		}
+		return false;
+    }
+    
+	public static boolean dfs(char[][] board, String words, int idx, int i, int j) {
+		if(idx==words.length()){
+			return true;
+		}
+		if(i<0||i==board.length||j<0||j==board[0].length){
+			return false;
+		}
+		if(board[i][j]!=words.charAt(idx)){
+			return false;
+		}
+		board[i][j] ^= 256;
+		boolean exist = dfs(board, words, idx+1, i, j+1)||dfs(board, words, idx+1, i, j-1)||
+				dfs(board, words, idx+1, i+1, j)||dfs(board, words, idx+1, i-1, j);
+		board[i][j] ^= 256;
+		return exist;
+	}
+}
+```
diff --git a/2019.01.14-leetcode257/Ostrichcrab.md b/2019.01.14-leetcode257/Ostrichcrab.md
new file mode 100644
index 000000000..04453ed9a
--- /dev/null
+++ b/2019.01.14-leetcode257/Ostrichcrab.md
@@ -0,0 +1,33 @@
+```
+/**
+ * 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:
+    void dfs(TreeNode* root, vector &str, string strpath)
+    {
+        if(root->left==nullptr&&root->right==nullptr){
+            str.push_back(strpath);
+            return;
+        }
+        if(root->left){
+            dfs(root->left,str,strpath+"->"+to_string(root->left->val));
+        }
+        if(root->right){
+            dfs(root->right,str,strpath+"->"+to_string(root->right->val));
+        }
+    }
+    vector binaryTreePaths(TreeNode* root) {
+        vector res;
+        if(root==nullptr) return res;
+        dfs(root,res,to_string(root->val));
+        return res;
+    }
+};
+```
diff --git a/2019.01.14-leetcode257/TheRocket.md b/2019.01.14-leetcode257/TheRocket.md
new file mode 100644
index 000000000..00d912e20
--- /dev/null
+++ b/2019.01.14-leetcode257/TheRocket.md
@@ -0,0 +1,33 @@
+```java
+/**
+ * Definition for a binary tree node.
+ * public class TreeNode {
+ *     int val;
+ *     TreeNode left;
+ *     TreeNode right;
+ *     TreeNode(int x) { val = x; }
+ * }
+ */
+class Solution {
+    public List binaryTreePaths(TreeNode root) {
+        List res = new ArrayList<>();
+        if (root != null) {
+            dfs(root, String.valueOf(root.val), res);
+        }
+        return res;
+    }
+
+    private void dfs(TreeNode root, String path, List res) {
+        if (root.left == null && root.right == null) {
+            res.add(path);
+            return;
+        }
+        if (root.left != null) {
+            dfs(root.left, path + "->" + root.left.val, res);
+        }
+        if (root.right != null) {
+            dfs(root.right, path + "->" + root.right.val, res);
+        }
+    }
+}
+```
diff --git a/2019.01.14-leetcode257/marguerite.md b/2019.01.14-leetcode257/marguerite.md
new file mode 100644
index 000000000..3a1264571
--- /dev/null
+++ b/2019.01.14-leetcode257/marguerite.md
@@ -0,0 +1,39 @@
+```
+ /**
+     * 递归方式
+     * @param root
+     * @return
+     */
+     
+ ```
+    public List binaryTreePaths(TreeNode root) {
+        if (root == null) {
+            return resultList;
+        }
+        List singleResult = new ArrayList<>();
+
+        getTreePath(root, singleResult);
+        return resultList;
+    }
+    
+```
+ /**
+     * DFS深度优先遍历
+     * @param resultList
+     * @param node
+     * @param singleResult
+     */
+```     
+    private void getTreePath(TreeNode node, List singleResult) {
+        singleResult.add(node.val + "");
+        if (node.left == null && node.right == null) {
+            resultList.add(getPath(singleResult));
+        }
+        if (node.left != null) {
+            getTreePath(node.left, new ArrayList<>(singleResult));
+        }
+        if (node.right != null) {
+            getTreePath(node.right, new ArrayList<>(singleResult));
+        }
+    }
+```
diff --git a/2019.01.14-leetcode257/sourcema.md b/2019.01.14-leetcode257/sourcema.md
new file mode 100644
index 000000000..d48b53171
--- /dev/null
+++ b/2019.01.14-leetcode257/sourcema.md
@@ -0,0 +1,25 @@
+# leetcode 257
+    class Solution {
+        public List binaryTreePaths(TreeNode root) {
+            List list = new ArrayList<>();
+            if (root == null) {
+                return list;
+            }
+            dfs(root, list,new String());
+            return list;
+        }
+        private void dfs(TreeNode root, List list,String ret) {
+            if (root.left==null&&root.right==null) {
+                ret+=root.val;
+                list.add(ret);
+                return;
+            }
+            ret += root.val + "->";
+            if(root.left!=null){
+            dfs(root.left,list,ret);
+            }
+            if(root.right!=null){
+            dfs(root.right,list,ret);
+            }
+        }
+    }
diff --git "a/2019.01.14-leetcode257/\344\272\214\345\217\211\346\240\221\347\232\204\346\211\200\346\234\211\350\267\257\345\276\204" "b/2019.01.14-leetcode257/\344\272\214\345\217\211\346\240\221\347\232\204\346\211\200\346\234\211\350\267\257\345\276\204"
new file mode 100644
index 000000000..2e9d87f64
--- /dev/null
+++ "b/2019.01.14-leetcode257/\344\272\214\345\217\211\346\240\221\347\232\204\346\211\200\346\234\211\350\267\257\345\276\204"
@@ -0,0 +1,17 @@
+给定一个二叉树,返回所有从根节点到叶子节点的路径。
+
+说明: 叶子节点是指没有子节点的节点。
+
+示例:
+
+输入:
+
+   1
+ /   \
+2     3
+ \
+  5
+
+输出: ["1->2->5", "1->3"]
+
+解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
diff --git "a/2019.01.14-leetcode257/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.14-leetcode257/\345\210\230\346\266\246\346\263\275(capture).md"
new file mode 100644
index 000000000..d6d4b1776
--- /dev/null
+++ "b/2019.01.14-leetcode257/\345\210\230\346\266\246\346\263\275(capture).md"
@@ -0,0 +1,23 @@
+```java
+    public List binaryTreePaths(TreeNode root) {
+
+        List res = new ArrayList<>();
+        if (root==null) return res;
+        deepsearch(root, "", res);
+        return res;
+    }
+
+    public void deepsearch(TreeNode node, String currStr, List res){
+
+        if (node.left==null&&node.right==null) {
+            currStr = currStr + node.val;
+            res.add(currStr);
+            return;
+        }
+
+        currStr = currStr + node.val + "->";
+
+        if (node.left!=null) deepsearch(node.left,currStr,res);
+        if (node.right!=null) deepsearch(node.right,currStr,res);
+    }
+```
diff --git "a/2019.01.14-leetcode257/\346\243\225\346\246\210\346\240\221.md" "b/2019.01.14-leetcode257/\346\243\225\346\246\210\346\240\221.md"
new file mode 100644
index 000000000..57e954076
--- /dev/null
+++ "b/2019.01.14-leetcode257/\346\243\225\346\246\210\346\240\221.md"
@@ -0,0 +1,32 @@
+```
+/**
+ * Definition for a binary tree node.
+ * public class TreeNode {
+ *     int val;
+ *     TreeNode left;
+ *     TreeNode right;
+ *     TreeNode(int x) { val = x; }
+ * }
+ */
+class Solution {
+    public List binaryTreePaths(TreeNode root) {
+        List res = new ArrayList<>();
+		if(null!=root){
+			DFS(root,"",res);
+		}
+		return res;
+    }
+    
+    public void DFS(TreeNode node,String path,List res){
+		if(node.left==null&&node.right==null){
+			res.add(path+node.val);
+		}
+		if(node.left!=null){
+			DFS(node.left,path+node.val+"->",res);
+		}
+		if(node.right!=null){
+			DFS(node.right,path+node.val+"->",res);
+		}
+	}
+}
+```
diff --git a/2019.01.15-leetcode46/Ostrichctab.md b/2019.01.15-leetcode46/Ostrichctab.md
new file mode 100644
index 000000000..843cd21c7
--- /dev/null
+++ b/2019.01.15-leetcode46/Ostrichctab.md
@@ -0,0 +1,29 @@
+```
+class Solution {
+public:
+    void dfs(vector& nums, vector> &res, vector t, vector &flag)
+    {
+        if(t.size()==nums.size()) {
+            res.push_back(t);
+            return ;
+        }
+        for(int i = 0; i> permute(vector& nums) {
+        vector> res;
+        vector t;
+        vector flag(nums.size(),0);
+        if(nums.size()==0) return res;
+        dfs(nums,res,t,flag);
+        return res;
+    }
+};
+```
diff --git a/2019.01.15-leetcode46/TheRocket.md b/2019.01.15-leetcode46/TheRocket.md
new file mode 100644
index 000000000..ee1ed8a9f
--- /dev/null
+++ b/2019.01.15-leetcode46/TheRocket.md
@@ -0,0 +1,31 @@
+```java
+class Solution {
+    public List> permute(int[] nums) {
+        List> res = new ArrayList<>();
+        dfs(nums, res, 0);
+        return res;
+    }
+
+    private void dfs(int[] nums, List> res, int s) {
+        if (s == nums.length) {
+            List list = new ArrayList<>(nums.length);
+            for (int num : nums) {
+                list.add(num);
+            }
+            res.add(list);
+            return;
+        }
+        for (int i = s; i < nums.length; ++i) {
+            swap(nums, i, s);
+            dfs(nums, res, s + 1);
+            swap(nums, i, s);
+        }
+    }
+
+    private void swap(int[] nums, int i, int j) {
+        int tmp = nums[i];
+        nums[i] = nums[j];
+        nums[j] = tmp;
+    }
+}
+```
diff --git a/2019.01.15-leetcode46/marguerite.md b/2019.01.15-leetcode46/marguerite.md
new file mode 100644
index 000000000..ec8050bf1
--- /dev/null
+++ b/2019.01.15-leetcode46/marguerite.md
@@ -0,0 +1,27 @@
+```
+public class Solution {
+    public List> permute(int[] nums) {
+        List> res = new ArrayList>();
+        ArrayList temp = new ArrayList();
+        dfs(res, nums, 0);
+        return res;
+    }
+    private void dfs(List> res, int[] nums, int j) {
+        if (j == nums.length) {
+            List temp = new ArrayList();
+            for (int num : nums) temp.add(num);
+            res.add(temp);
+        }
+        for (int i = j; i < nums.length; i++) {
+            swap(nums, i, j);
+            dfs(res, nums, j+1);
+            swap(nums, i, j);
+        }
+    }
+    private void swap(int[] nums, int m, int n) {
+        int temp = nums[m];
+        nums[m] = nums[n];
+        nums[n] = temp;
+    }
+}
+```
diff --git "a/2019.01.15-leetcode46/\345\205\250\346\216\222\345\210\227" "b/2019.01.15-leetcode46/\345\205\250\346\216\222\345\210\227"
new file mode 100644
index 000000000..0806df0a2
--- /dev/null
+++ "b/2019.01.15-leetcode46/\345\205\250\346\216\222\345\210\227"
@@ -0,0 +1,14 @@
+给定一个没有重复数字的序列,返回其所有可能的全排列。
+
+示例:
+
+输入: [1,2,3]
+输出:
+[
+  [1,2,3],
+  [1,3,2],
+  [2,1,3],
+  [2,3,1],
+  [3,1,2],
+  [3,2,1]
+]
diff --git "a/2019.01.15-leetcode46/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.15-leetcode46/\345\210\230\346\266\246\346\263\275(capture).md"
new file mode 100644
index 000000000..f76ad5e90
--- /dev/null
+++ "b/2019.01.15-leetcode46/\345\210\230\346\266\246\346\263\275(capture).md"
@@ -0,0 +1,36 @@
+```java
+    public List> permute(int[] nums) {
+        List> res = new ArrayList<>();
+        List currRes = new ArrayList<>();
+        fenzhi(nums,0,currRes,res);
+        return res;
+    }
+
+    public void fenzhi(int[] nums, int deep, List currRes, List> res){
+        if (nums.length==1){
+            currRes.add(nums[0]);
+            List tempRes = new ArrayList<>();
+            for (int i=0;ideep){
+                currRes.remove(currRes.size()-1);
+            }
+            int[] nextNums = new int[nums.length-1];
+            for (int j=0,k=0;j> permute(int[] nums) {
+        List> res = new ArrayList<>();
+        if(null==nums||nums.length==0){
+        	return res;
+        }
+        List l0 = new ArrayList<>();
+        l0.add(nums[0]);
+        res.add(l0);
+        for(int i=1;i> new_ans = new ArrayList>();
+        	for(int j=0;j<=i;++j){
+        		for(List l:res){
+        			List new_l = new ArrayList(l);
+        			new_l.add(j, nums[i]);
+        			new_ans.add(new_l);
+        		}
+        	}
+        	res = new_ans;
+        }
+        return res;
+    }
+    
+    public static void main(String[] args) {
+    	int[] nums = {1,2,3};
+		System.out.println(permute(nums));
+	}
+}
+```
diff --git a/2019.01.16-leetcode47/Ostrichcrab.md b/2019.01.16-leetcode47/Ostrichcrab.md
new file mode 100644
index 000000000..9bbe68a96
--- /dev/null
+++ b/2019.01.16-leetcode47/Ostrichcrab.md
@@ -0,0 +1,14 @@
+```
+class Solution {
+public:
+    vector> permuteUnique(vector& nums) {
+        vector> res;
+        sort(nums.begin(),nums.end());
+        do
+        {
+            res.push_back(nums);
+        }while(next_permutation(nums.begin(),nums.end()));
+        return res;
+    }
+};
+```
diff --git a/2019.01.16-leetcode47/TheRocket.md b/2019.01.16-leetcode47/TheRocket.md
new file mode 100644
index 000000000..9e249df28
--- /dev/null
+++ b/2019.01.16-leetcode47/TheRocket.md
@@ -0,0 +1,43 @@
+```java
+class Solution {
+    public List> permuteUnique(int[] nums) {
+        List> res = new ArrayList<>();
+        dfs(nums, res, 0);
+        return res;
+    }
+
+    private void dfs(int[] nums, List> res, int s) {
+        if (s == nums.length) {
+            List list = new ArrayList<>(nums.length);
+            for (int num : nums) {
+                list.add(num);
+            }
+            res.add(list);
+            return;
+        }
+        for (int i = s; i < nums.length; ++i) {
+            if (isDuplicate(nums, s, i)) {
+                continue;
+            }
+            swap(nums, i, s);
+            dfs(nums, res, s + 1);
+            swap(nums, i, s);
+        }
+    }
+
+    private boolean isDuplicate(int[] nums, int s, int e) {
+        for (int i = s; i < e; ++i) {
+            if (nums[i] == nums[e]) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private void swap(int[] nums, int i, int j) {
+        int tmp = nums[i];
+        nums[i] = nums[j];
+        nums[j] = tmp;
+    }
+}
+```
diff --git a/2019.01.16-leetcode47/marguerite.md b/2019.01.16-leetcode47/marguerite.md
new file mode 100644
index 000000000..2ec7cdc0a
--- /dev/null
+++ b/2019.01.16-leetcode47/marguerite.md
@@ -0,0 +1,34 @@
+#使用递归
+
+```
+public class Solution {
+    public List> permuteUnique(int[] nums) {
+        List> result = new ArrayList>();
+        if (nums.length == 0)
+            return null;
+        Arrays.sort(nums);
+        getResult(result,nums,new ArrayList(),0,new int[nums.length]);
+        return result;
+    }
+ 
+    public static void getResult(List> result,int[] nums,List ans,int num,int[] pos){
+        if( num == nums.length){
+            result.add(new ArrayList(ans));
+            return ;
+        }
+        for( int i = 0 ; i> res = new ArrayList>();
+
+    public List> permuteUnique(int[] nums) {
+
+        int len = nums.length;
+        if (len==0) return res;
+        huisu(0,len,nums);
+        return res;
+    }
+
+    public void huisu(int deep, int len, int[] nums){
+
+        if (deep==len-1){
+            List tempList = new ArrayList<>();
+            for (int i=0;i> combine(int n, int k) {
+        vector> res;
+        vector out;
+        helper(n, k, 1, out, res);
+        return res;
+    }
+    void helper(int n, int k, int level, vector& out, vector>& res) {
+        if (out.size() == k) res.push_back(out);
+        for (int i = level; i <= n; ++i) {
+            out.push_back(i);
+            helper(n, k, i + 1, out, res);
+            out.pop_back();
+        }
+    }
+};
+```
diff --git a/2019.01.17-leetcode77/TheRocket.md b/2019.01.17-leetcode77/TheRocket.md
new file mode 100644
index 000000000..fce0e875b
--- /dev/null
+++ b/2019.01.17-leetcode77/TheRocket.md
@@ -0,0 +1,22 @@
+```java
+class Solution {
+    public List> combine(int n, int k) {
+        List> res = new ArrayList<>();
+        List list = new ArrayList<>(k);
+        dfs(n, k, 1, res, list);
+        return res;
+    }
+
+    private void dfs(int n, int k, int s, List> res, List list) {
+        if (list.size() == k) {
+            res.add(new ArrayList<>(list));
+            return;
+        }
+        for (int i = s; i <= n; ++i) {
+            list.add(i);
+            dfs(n, k, i + 1, res, list);
+            list.remove(list.size() - 1);
+        }
+    }
+}
+```
diff --git a/2019.01.17-leetcode77/sourcema.md b/2019.01.17-leetcode77/sourcema.md
new file mode 100644
index 000000000..6e640b64c
--- /dev/null
+++ b/2019.01.17-leetcode77/sourcema.md
@@ -0,0 +1,20 @@
+# leetcode 77
+    class Solution {
+    public List> combine(int n, int k) {
+        List> res = new ArrayList<>();
+        List list = new ArrayList<>();
+        dfs(n, k, res, list, 1);
+        return res;
+    }
+    public void dfs(int n, int k, List> res, List list, int start){
+        if(list.size() == k){
+            res.add(new ArrayList(list));
+            return;
+        }
+        for(int i = start; i <= n; i++){
+            list.add(i);
+            dfs(n, k, res, list, i + 1);
+            list.remove(list.size() - 1);
+        }
+    }
+}
diff --git "a/2019.01.17-leetcode77/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.17-leetcode77/\345\210\230\346\266\246\346\263\275(capture).md"
new file mode 100644
index 000000000..8b00263d7
--- /dev/null
+++ "b/2019.01.17-leetcode77/\345\210\230\346\266\246\346\263\275(capture).md"
@@ -0,0 +1,28 @@
+```java
+    public List> combine(int n, int k) {
+
+        List> res = new ArrayList<>();
+        int[] box = new int[k];
+        fenzhi(0,0,n,k,box,res);
+
+        return res;
+    }
+
+    public void fenzhi(int deep, int index, int n, int k, int[] box, List> res){
+
+        if (deep==k){
+            List tempList = new ArrayList<>();
+            for (int i=0;i> combine(int n, int k) {
+        List> res = new ArrayList<>();
+        combine(res, new ArrayList(), 1, n, k);
+        return res;
+    }
+    
+    public static void combine(List> res,List comb,int start,int n,int k){
+    	if(k==0){
+    		res.add(new ArrayList(comb));
+    		return;
+    	}
+    	
+    	for(int i=start;i<=n;i++){
+    		comb.add(i);
+    		combine(res, comb, i+1, n, k-1);
+    		comb.remove(comb.size()-1);
+    	}
+    }
+    
+    public static void main(String[] args) {
+		List> res = combine(5, 2);
+		System.out.println(res);
+	}
+}
+```
diff --git "a/2019.01.17-leetcode77/\347\273\204\345\220\210" "b/2019.01.17-leetcode77/\347\273\204\345\220\210"
new file mode 100644
index 000000000..f69606127
--- /dev/null
+++ "b/2019.01.17-leetcode77/\347\273\204\345\220\210"
@@ -0,0 +1,14 @@
+给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
+
+示例:
+
+输入: n = 4, k = 2
+输出:
+[
+  [2,4],
+  [3,4],
+  [2,3],
+  [1,2],
+  [1,3],
+  [1,4],
+]
diff --git a/2019.01.18-leetcode39/Ostrichcrab.md b/2019.01.18-leetcode39/Ostrichcrab.md
new file mode 100644
index 000000000..25b5fd92d
--- /dev/null
+++ b/2019.01.18-leetcode39/Ostrichcrab.md
@@ -0,0 +1,24 @@
+```
+class Solution {
+public:
+    void dfs(vector candidates, int start, int target, vector item, vector>& res)
+    {
+        if(target<0) return;
+        if(target==0) {
+            res.push_back(item);
+            return ;
+        }
+        for(int i = start; i < candidates.size(); i++){
+            item.push_back(candidates[i]);
+            dfs(candidates,i,target-candidates[i],item,res);
+            item.pop_back();
+        }
+    }
+    vector> combinationSum(vector& candidates, int target) {
+        vector> res;
+        vector item;
+        dfs(candidates,0,target,item,res);
+        return res;
+    }
+};
+```
diff --git a/2019.01.18-leetcode39/TheRocket.md b/2019.01.18-leetcode39/TheRocket.md
new file mode 100644
index 000000000..69c7d7f80
--- /dev/null
+++ b/2019.01.18-leetcode39/TheRocket.md
@@ -0,0 +1,24 @@
+```java
+class Solution {
+    public List> combinationSum(int[] candidates, int target) {
+        List> res = new ArrayList<>();
+        dfs(candidates, target, 0, res, new ArrayList());
+        return res;
+    }
+
+    private void dfs(int[] candidates, int target, int s, List> res, ArrayList list) {
+        if (target < 0) {
+            return;
+        }
+        if (target == 0) {
+            res.add(new ArrayList<>(list));
+            return;
+        }
+        for (int i = s; i < candidates.length; ++i) {
+            list.add(candidates[i]);
+            dfs(candidates, target - candidates[i], i, res, list);
+            list.remove(list.size() - 1);
+        }
+    }
+}
+```
diff --git a/2019.01.18-leetcode39/sourcema.md b/2019.01.18-leetcode39/sourcema.md
new file mode 100644
index 000000000..a7c22326e
--- /dev/null
+++ b/2019.01.18-leetcode39/sourcema.md
@@ -0,0 +1,32 @@
+# leetcode 39
+    class Solution {
+    public List> combinationSum(int[] candidates, int target) {
+         List> res = new ArrayList<>();
+        if (candidates == null || candidates.length == 0 || target <= 0) {
+            return res;
+        }
+        Arrays.sort(candidates);
+        combination(res,candidates,new ArrayList(),target,0,candidates.length);
+        return res;
+    }
+    private static void combination(List> res,int [] arr, ArrayList list,
+                                    int target, int index, int length) {
+        if (target == 0) {
+            ArrayList temp=new ArrayList<>(list);
+            Collections.sort(temp);
+            if (!res.contains(temp)) {
+                res.add(new ArrayList(temp));
+            }
+            return;
+        }
+        if (index >= length) {
+            return;
+        }
+        for (int i = index; i> combinationSum(int[] candidates, int target) {
+
+        List> res = new ArrayList<>();
+        List box = new ArrayList<>();
+        Arrays.sort(candidates);
+
+        for (int i=0;i(),res);
+        }
+
+        return res;
+    }
+
+    public void huisu(int currSum, int target, int index, int[] candidates, List box, List> res){
+
+        if (index==candidates.length)return;
+        int count = 0;
+        while (currSumtarget) break;
+            box.add(candidates[index]);
+            count++;
+            if (currSum==target){
+                res.add(new ArrayList(box));
+                break;
+            }
+            for (int i=index+1;i> combinationSum(int[] candidates, int target) {
+        List> res = new ArrayList<>();
+    	if(candidates.length==0||null==candidates){
+    		return res;
+    	}
+        comb(res, candidates, new ArrayList(), target, 0,0);
+        return res; 
+    }
+    
+    public void comb(List> res,int[] candidates,List com,int target,int start,int sum){
+    	if(sum==target){
+    		res.add(new ArrayList<>(com));
+    		return;
+    	}else if(sum>target){
+    		return;
+    	}
+    	
+    	for(int i=start;i> result;
+	vector> combinationSum2(vector& candidates, int target) {
+		sort(candidates.begin(), candidates.end());
+		combinate(candidates, candidates.size() - 1, {}, target);
+		return result;
+	}
+	void combinate(vector& candidates, int pos, vectorcontain, int target)
+	{
+		if (target == 0)
+			result.push_back(contain);
+		if (target < 0)
+			return;
+		for (int i = pos; i >= 0; i--)
+		{
+			if (i != pos && candidates[i] == candidates[i + 1]) //important!
+				continue;
+			contain.push_back(candidates[i]);
+			combinate(candidates, i - 1, contain, target - candidates[i]);
+			contain.pop_back();
+		}
+	}
+};
+```
diff --git a/2019.01.19-leetcode40/TheRocket.md b/2019.01.19-leetcode40/TheRocket.md
new file mode 100644
index 000000000..1a610de3b
--- /dev/null
+++ b/2019.01.19-leetcode40/TheRocket.md
@@ -0,0 +1,30 @@
+```java
+class Solution {
+    public List> combinationSum2(int[] candidates, int target) {
+        Arrays.sort(candidates);
+        List> res = new ArrayList<>();
+        dfs(candidates, target, 0, res, new ArrayList<>());
+        return res;
+    }
+
+    private void dfs(int[] candidates, int target, int s, List> res, ArrayList list) {
+        if (target < 0) {
+            return;
+        }
+        if (target == 0) {
+            res.add(new ArrayList<>(list));
+            return;
+        }
+        for (int i = s; i < candidates.length; ++i) {
+            // 不允许重复使用
+            if (i > s && candidates[i] == candidates[i - 1]) {
+                continue;
+            }
+            list.add(candidates[i]);
+            // 传入下一层的起始参数为 i + 1
+            dfs(candidates, target - candidates[i], i + 1, res, list);
+            list.remove(list.size() - 1);
+        }
+    }
+}
+```
diff --git a/2019.01.19-leetcode40/sourcema.md b/2019.01.19-leetcode40/sourcema.md
new file mode 100644
index 000000000..80d205e69
--- /dev/null
+++ b/2019.01.19-leetcode40/sourcema.md
@@ -0,0 +1,27 @@
+# leetcode 40
+    class Solution {
+    public List> combinationSum2(int[] candidates, int target) {
+         List> res = new ArrayList<>();
+        if (candidates == null || candidates.length == 0 || target <= 0) {
+            return res;
+        }
+        Arrays.sort(candidates);//
+        combination(res,candidates,new ArrayList(),target,0);
+        return res;
+    }
+    private static void combination(List> res, int[] candidates, ArrayList list,
+                                    int target, int index) {
+        if (target == 0) {
+            if (!res.contains(list))
+            res.add(new ArrayList(list));
+            return;
+        }
+        if (index>=candidates.length||target < candidates[index]) {
+            return;
+        }
+            list.add(candidates[index]);
+            combination(res,candidates,list,target-candidates[index],index+1);
+            list.remove(list.size() - 1);
+            combination(res,candidates,list,target,index+1);
+    }
+}
diff --git "a/2019.01.19-leetcode40/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.19-leetcode40/\345\210\230\346\266\246\346\263\275(capture).md"
new file mode 100644
index 000000000..bf61dd823
--- /dev/null
+++ "b/2019.01.19-leetcode40/\345\210\230\346\266\246\346\263\275(capture).md"
@@ -0,0 +1,33 @@
+```java
+   public void search(int[] candidates, int target, List box, List> res, int n, boolean flag) {
+
+        if (target==0){
+            res.add(new ArrayList(box));
+        }
+
+        if(n == candidates.length || target < candidates[n])
+            return;
+
+        if (flag&&n>0&&n> combinationSum(int[] candidates, int target) {
+        List> res = new ArrayList<>();
+        if(candidates == null || candidates.length == 0) {
+            return res;
+        }
+        Arrays.sort(candidates);
+        List box = new ArrayList<>();
+        search(candidates, target, box, res, 0, true);
+        return res;
+    }
+```
diff --git "a/2019.01.19-leetcode40/\346\243\225\346\246\210\346\240\221.md" "b/2019.01.19-leetcode40/\346\243\225\346\246\210\346\240\221.md"
new file mode 100644
index 000000000..f1bc1bea9
--- /dev/null
+++ "b/2019.01.19-leetcode40/\346\243\225\346\246\210\346\240\221.md"
@@ -0,0 +1,26 @@
+```
+class Solution {
+    public List> combinationSum2(int[] candidates, int target) {
+        List> res = new ArrayList<>();
+        Arrays.sort(candidates);
+        comb(res, new ArrayList(), candidates, target, 0);
+        return res;
+    }
+    
+    public static void comb(List> res,List com,int[] candidates,int target,int start){
+    	if(target==0){
+    		res.add(new ArrayList<>(com));
+    		return;
+    	}
+    	if(target<0)	return;
+    	
+    	for(int i=start;istart&&candidates[i]==candidates[i-1])
+    			continue;
+    		com.add(candidates[i]);
+    		comb(res, com, candidates, target-candidates[i], i+1);
+    		com.remove(com.size()-1);
+    	}
+    }
+}
+```
diff --git "a/2019.01.19-leetcode40/\347\273\204\345\220\210\346\200\273\345\222\214II" "b/2019.01.19-leetcode40/\347\273\204\345\220\210\346\200\273\345\222\214II"
new file mode 100644
index 000000000..2c0250fdb
--- /dev/null
+++ "b/2019.01.19-leetcode40/\347\273\204\345\220\210\346\200\273\345\222\214II"
@@ -0,0 +1,26 @@
+给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
+
+candidates 中的每个数字在每个组合中只能使用一次。
+
+说明:
+
+所有数字(包括目标数)都是正整数。
+解集不能包含重复的组合。 
+示例 1:
+
+输入: candidates = [10,1,2,7,6,1,5], target = 8,
+所求解集为:
+[
+  [1, 7],
+  [1, 2, 5],
+  [2, 6],
+  [1, 1, 6]
+]
+示例 2:
+
+输入: candidates = [2,5,2,1,2], target = 5,
+所求解集为:
+[
+  [1,2,2],
+  [5]
+]
diff --git a/2019.01.20-leetcode216/Ostrichcrab.md b/2019.01.20-leetcode216/Ostrichcrab.md
new file mode 100644
index 000000000..53263656b
--- /dev/null
+++ b/2019.01.20-leetcode216/Ostrichcrab.md
@@ -0,0 +1,25 @@
+```
+class Solution {
+public:
+    void dfs(vector> &res, vector sol, int k, int n){
+        if(sol.size()==k&&n==0){
+            res.push_back(sol);
+            return ;
+        }
+        if(sol.size()> combinationSum3(int k, int n) {
+        vector> res;
+        vector sol;
+        dfs(res,sol,k,n);
+        return res;
+    }
+};
+```
diff --git a/2019.01.20-leetcode216/TheRocket.md b/2019.01.20-leetcode216/TheRocket.md
new file mode 100644
index 000000000..fe80e06cf
--- /dev/null
+++ b/2019.01.20-leetcode216/TheRocket.md
@@ -0,0 +1,23 @@
+```java
+class Solution {
+    public List> combinationSum3(int k, int n) {
+        List> res = new ArrayList<>();
+        dfs(k, n, 1, res, new ArrayList<>(k));
+        return res;
+    }
+
+    private void dfs(int k, int n, int s, List> res, ArrayList list) {
+        if (list.size() == k) {
+            if (n == 0) {
+                res.add(new ArrayList<>(list));
+            }
+            return;
+        }
+        for (int i = s; i <= 9; ++i) {
+            list.add(i);
+            dfs(k, n - i, i + 1, res, list);
+            list.remove(list.size() - 1);
+        }
+    }
+}
+```
diff --git a/2019.01.20-leetcode216/sourcema.md b/2019.01.20-leetcode216/sourcema.md
new file mode 100644
index 000000000..6ff7bc7c8
--- /dev/null
+++ b/2019.01.20-leetcode216/sourcema.md
@@ -0,0 +1,25 @@
+# leetcode 216
+    class Solution {
+    public List> combinationSum3(int k, int n) {
+         List> res = new ArrayList<>();
+        if (k <= 0 || n <= 0) {
+            return res;
+        }
+        find(res, new ArrayList(), k, n,1);
+        return res;
+    }
+    private static void find(List> res, ArrayList list, int k, int n,int num) {
+        if (list.size() == k && n == 0) {
+            res.add(new ArrayList(list));
+            return;
+        }
+        if (list.size() >= k) {
+            return;
+        }
+        for (int i = num; i <=9&&i<=n ; i++) {
+            list.add(i);
+            find(res,list,k,n-i,i+1);
+            list.remove(list.size() - 1);
+        }
+    }
+}
diff --git "a/2019.01.20-leetcode216/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.20-leetcode216/\345\210\230\346\266\246\346\263\275(capture).md"
new file mode 100644
index 000000000..ff2923a36
--- /dev/null
+++ "b/2019.01.20-leetcode216/\345\210\230\346\266\246\346\263\275(capture).md"
@@ -0,0 +1,26 @@
+```java
+    public List> combinationSum3(int k, int n) {
+
+        List> res = new ArrayList<>();
+        List box = new ArrayList<>();
+        search(k,0,n,box,res);
+        return res;
+    }
+
+    public void search(int k, int lastCount, int n, List box, List> res){
+
+
+        if (k<0||n<0) return;
+
+        if (n==0&&k==0){
+            res.add(new ArrayList(box));
+        }
+
+        for (int i=lastCount+1;i<=n&&i<10;i++){
+            box.add(i);
+            search(k-1,i,n-i,box,res);
+            box.remove(box.size()-1);
+        }
+
+    }
+```
diff --git "a/2019.01.20-leetcode216/\346\243\225\346\246\210\346\240\221.md" "b/2019.01.20-leetcode216/\346\243\225\346\246\210\346\240\221.md"
new file mode 100644
index 000000000..7b2cd18b5
--- /dev/null
+++ "b/2019.01.20-leetcode216/\346\243\225\346\246\210\346\240\221.md"
@@ -0,0 +1,24 @@
+```
+class Solution {
+    public List> combinationSum3(int k, int n) {
+    	List> res = new ArrayList<>();
+    	if(k<=0||n<=0){
+    		return res;
+    	}
+        comb(res, new ArrayList(),k, 1, n);
+        return res;
+    }
+    
+     public static void comb(List> res,List com,int k,int start,int n){
+    	if(k==com.size()&&0==n){
+    		res.add(new ArrayList<>(com));
+    		return;
+    	}
+    	for(int i=start;i<=9;i++){
+    		com.add(i);
+    		comb(res, com, k,i+1,n-i);
+    		com.remove(com.size()-1);
+    	}
+    }
+}
+```
diff --git "a/2019.01.20-leetcode216/\347\273\204\345\220\210\346\200\273\345\222\214III" "b/2019.01.20-leetcode216/\347\273\204\345\220\210\346\200\273\345\222\214III"
new file mode 100644
index 000000000..91a4c55b9
--- /dev/null
+++ "b/2019.01.20-leetcode216/\347\273\204\345\220\210\346\200\273\345\222\214III"
@@ -0,0 +1,14 @@
+找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
+
+说明:
+
+所有数字都是正整数。
+解集不能包含重复的组合。 
+示例 1:
+
+输入: k = 3, n = 7
+输出: [[1,2,4]]
+示例 2:
+
+输入: k = 3, n = 9
+输出: [[1,2,6], [1,3,5], [2,3,4]]
diff --git a/2019.01.21-leetcode78/Ostrichcrab.md b/2019.01.21-leetcode78/Ostrichcrab.md
new file mode 100644
index 000000000..754be0888
--- /dev/null
+++ b/2019.01.21-leetcode78/Ostrichcrab.md
@@ -0,0 +1,34 @@
+```
+class Solution {
+public:
+    vector> subsets(vector& nums) {
+        int n = nums.size();
+        int m = 1<> res(m,vector());
+        for(int i = 0; i < n; i++)
+            for(int j =  0; j < m; j++)
+                if((j>>i)&1)
+                    res[j].push_back(nums[i]);
+        return res;
+    }
+};
+```
+```
+class Solution {
+public:
+    vector> subsets(vector& nums) {
+        int n = nums.size();
+        int m = 1<> res(m,vector());
+        // for(int i = 0; i < n; i++)
+        //     for(int j =  0; j < m; j++)
+        //         if((j>>i)&1)
+        //             res[j].push_back(nums[i]);
+        for(int i = 0; i < m; i++)
+            for(int j = 0; j < n; j++)
+                if((i>>j)&1)
+                    res[i].push_back(nums[j]);
+        return res;
+    }
+};
+```
diff --git a/2019.01.21-leetcode78/TheRocket.md b/2019.01.21-leetcode78/TheRocket.md
new file mode 100644
index 000000000..02749ee93
--- /dev/null
+++ b/2019.01.21-leetcode78/TheRocket.md
@@ -0,0 +1,18 @@
+```java
+class Solution {
+    public List> subsets(int[] nums) {
+        List> res = new ArrayList<>();
+        dfs(0, nums, res, new ArrayList<>());
+        return res;
+    }
+
+    private void dfs(int s, int[] nums, List> res, List list) {
+        res.add(new ArrayList<>(list));
+        for (int i = s; i < nums.length; ++i) {
+            list.add(nums[i]);
+            dfs(i + 1, nums, res, list);
+            list.remove(list.size() - 1);
+        }
+    }
+}
+```
diff --git a/2019.01.21-leetcode78/marguerite.md b/2019.01.21-leetcode78/marguerite.md
new file mode 100644
index 000000000..f8cd55255
--- /dev/null
+++ b/2019.01.21-leetcode78/marguerite.md
@@ -0,0 +1,19 @@
+```
+
+public class Solution {
+    public List> subsets(int[] nums) {
+        List> res = new ArrayList>();
+        res.add(new ArrayList());
+        for (int num : nums) {  // ①从数组中取出每个元素
+            int size = res.size();
+            for (int i = 0; i < size; i++) {
+                List temp = new ArrayList<>(res.get(i));  // ②逐一取出中间结果集
+                temp.add(num);  // ③将 num 放入中间结果集
+                res.add(temp);  // ④加入到结果集中
+            }
+        }
+        return res;
+    }
+
+
+```
diff --git a/2019.01.21-leetcode78/sourcema.md b/2019.01.21-leetcode78/sourcema.md
new file mode 100644
index 000000000..9391cde27
--- /dev/null
+++ b/2019.01.21-leetcode78/sourcema.md
@@ -0,0 +1,23 @@
+# leetcode 78
+    class Solution {
+    public List> subsets(int[] nums) {
+         List> res = new ArrayList<>();
+        if (nums == null || nums.length == 0) {
+            return res;
+        }
+        find(res,new ArrayList(), nums,0);
+        res.add(new ArrayList());//add empty set
+        return res;
+    }
+     private  void find(List> res, ArrayList list, int[] nums,int index) {
+        if (index >= nums.length) {
+            return;
+        }
+        for (int i = index; i < nums.length; i++) {
+            list.add(nums[i]);
+            res.add(new ArrayList(list));
+            find(res,list,nums,i+1);
+            list.remove(list.size() - 1);
+        }
+    }
+}
diff --git "a/2019.01.21-leetcode78/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.21-leetcode78/\345\210\230\346\266\246\346\263\275(capture).md"
new file mode 100644
index 000000000..1113679fb
--- /dev/null
+++ "b/2019.01.21-leetcode78/\345\210\230\346\266\246\346\263\275(capture).md"
@@ -0,0 +1,58 @@
+```java
+    public List> subsets(int[] nums) {
+
+        List> res = new ArrayList<>();
+        if (nums==null||nums.length==0) return res;
+        List box = new ArrayList<>();
+        List allList = new ArrayList<>();
+
+        search(0,nums.length,nums,box,allList,res);
+
+        return res;
+    }
+
+    public void search(int startNum, int endNum, int[] nums, List box, List allList, List> res){
+
+        if (startNum==0) {
+            res.add(new ArrayList<>());
+            startNum++;
+        }
+        if (endNum==nums.length) {
+            for (int i : nums){
+                allList.add(i);
+            }
+            res.add(allList);
+            endNum--;
+        }
+        if (startNum==endNum){
+            digui(startNum, 0, nums, box, allList, res, true);
+            return;
+        }
+        if (startNum>endNum){
+            return;
+        }
+
+        digui(startNum, 0, nums, box, allList, res, false);
+
+        search(startNum+1,endNum-1,nums,box,allList,res);
+
+    }
+
+    public void digui(int k, int index, int[] nums, List box, List allList, List> res, boolean isEqual){
+        if (k==0) {
+            res.add(new ArrayList<>(box));
+            if (isEqual) return;
+            ArrayList tempList = new ArrayList<>(allList);
+            if(tempList.removeAll(box)) {
+                res.add(tempList);
+            }
+            return;
+        }
+
+        for (int i=index;i> subsets(int[] nums) {
+        List> res = new ArrayList<>();
+        for(int i=0;i<=nums.length;i++){
+        	comb(res, new ArrayList(), nums, 0, i);        	
+        }
+        return res;
+    }
+    
+    public void comb(List> res,List com,int[] nums,int start,int size){
+    	if(com.size()==size){
+    		res.add(new ArrayList<>(com));
+    		return;
+    	}
+    	
+    	for(int i=start;i<=nums.length-1;i++){
+    		com.add(nums[i]);
+    		comb(res, com, nums, i+1,size);
+    		com.remove(com.size()-1);
+    	}
+    }
+}
+```
diff --git a/2019.01.22-leetcode90/Ostrichcrab.md b/2019.01.22-leetcode90/Ostrichcrab.md
new file mode 100644
index 000000000..3fa83f08b
--- /dev/null
+++ b/2019.01.22-leetcode90/Ostrichcrab.md
@@ -0,0 +1,23 @@
+```
+class Solution {
+public:
+    void dfs(vector& nums, int pos, vector& path, vector>& result){
+        if(pos==nums.size()) return ;
+        for(int i = pos; i < nums.size(); i++){
+            path.push_back(nums[i]);
+            result.push_back(path);
+            dfs(nums,i+1,path,result);
+            path.pop_back();
+            while(nums[i]==nums[i+1]) i++;
+        }
+    }
+    vector> subsetsWithDup(vector& nums) {
+        vector path;
+        vector> result;
+        result.push_back(path);
+        sort(nums.begin(),nums.end());
+        dfs(nums,0,path,result);
+        return result;
+    }
+};
+```
diff --git a/2019.01.22-leetcode90/TheRocket.md b/2019.01.22-leetcode90/TheRocket.md
new file mode 100644
index 000000000..953e7f52c
--- /dev/null
+++ b/2019.01.22-leetcode90/TheRocket.md
@@ -0,0 +1,22 @@
+```java
+class Solution {
+    public List> subsetsWithDup(int[] nums) {
+        Arrays.sort(nums);
+        List> res = new ArrayList<>();
+        dfs(0, nums, res, new ArrayList<>());
+        return res;
+    }
+
+    private void dfs(int s, int[] nums, List> res, ArrayList list) {
+        res.add(new ArrayList<>(list));
+        for (int i = s; i < nums.length; ++i) {
+            if (i > s && nums[i] == nums[i - 1]) {
+                continue;
+            }
+            list.add(nums[i]);
+            dfs(i + 1, nums, res, list);
+            list.remove(list.size() - 1);
+        }
+    }
+}
+```
diff --git a/2019.01.22-leetcode90/marguerite.md b/2019.01.22-leetcode90/marguerite.md
new file mode 100644
index 000000000..320f114e0
--- /dev/null
+++ b/2019.01.22-leetcode90/marguerite.md
@@ -0,0 +1,23 @@
+```
+public class Solution {
+    public List> subsetsWithDup(int[] nums) {
+        List> result=new ArrayList<>();
+        List list=new ArrayList<>();
+        Arrays.sort(nums);
+        backtracking(result, nums, list, 0);
+        return result;
+    }
+     
+    public void backtracking(List> result,int nums[],List list,int start) {
+        result.add(new ArrayList<>(list));
+        for(int i=start;istart&&nums[i]==nums[i-1]) continue;    //跳过重复的
+            list.add(nums[i]);
+            backtracking(result, nums, list, i+1);
+            list.remove(list.size()-1);
+             
+        }
+    }
+}
+
+```
diff --git "a/2019.01.22-leetcode90/\345\255\220\351\233\206II" "b/2019.01.22-leetcode90/\345\255\220\351\233\206II"
new file mode 100644
index 000000000..c9b558328
--- /dev/null
+++ "b/2019.01.22-leetcode90/\345\255\220\351\233\206II"
@@ -0,0 +1,16 @@
+给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
+
+说明:解集不能包含重复的子集。
+
+示例:
+
+输入: [1,2,2]
+输出:
+[
+  [2],
+  [1],
+  [1,2,2],
+  [2,2],
+  [1,2],
+  []
+]
diff --git "a/2019.01.22-leetcode90/\346\243\225\346\246\210\346\240\221.md" "b/2019.01.22-leetcode90/\346\243\225\346\246\210\346\240\221.md"
new file mode 100644
index 000000000..4a6af6e53
--- /dev/null
+++ "b/2019.01.22-leetcode90/\346\243\225\346\246\210\346\240\221.md"
@@ -0,0 +1,27 @@
+```
+class Solution {
+    public List> subsetsWithDup(int[] nums) {
+        Arrays.sort(nums);
+        List> res = new ArrayList<>();
+        comb(res, new ArrayList(), nums, 0);
+        return res;  
+    }
+    
+        public void comb(List> res,List com,int[] nums,int start){
+    	if(nums.length>=com.size()){
+    		res.add(new ArrayList<>(com));
+    	}
+    	int i = start;
+    	while(i> partition(string s) {
+        vector > ret;
+        if(s.empty()) return ret;
+        
+        vector path;
+        dfs(0, s, path, ret);
+        
+        return ret;
+    }
+    
+    void dfs(int index, string& s, vector& path, vector >& ret) {
+        if(index == s.size()) {
+            ret.push_back(path);
+            return;
+        }
+        for(int i = index; i < s.size(); ++i) {
+            if(isPalindrome(s, index, i)) {
+                path.push_back(s.substr(index, i - index + 1));
+                dfs(i+1, s, path, ret);
+                path.pop_back();
+            }
+        }
+    }
+    
+    bool isPalindrome(const string& s, int start, int end) {
+        while(start <= end) {
+            if(s[start++] != s[end--])
+                return false;
+        }
+        return true;
+    }
+};
+```
diff --git a/2019.01.23-leetcode131/TheRocket.md b/2019.01.23-leetcode131/TheRocket.md
new file mode 100644
index 000000000..c8fb6ac67
--- /dev/null
+++ b/2019.01.23-leetcode131/TheRocket.md
@@ -0,0 +1,36 @@
+```java
+class Solution {
+    public List> partition(String s) {
+        List> res = new ArrayList<>();
+        List list = new ArrayList<>();
+        dfs(s, res, list);
+        return res;
+    }
+
+    private void dfs(String s, List> res, List list) {
+        if (s.length() == 0) {
+            res.add(new ArrayList<>(list));
+            return;
+        }
+        for (int i = 1; i <= s.length(); ++i) {
+            String sub = s.substring(0, i);
+            if (isPalindrome(sub)) {
+                list.add(sub);
+                dfs(s.substring(i), res, list);
+                list.remove(list.size() - 1);
+            }
+        }
+    }
+
+    private boolean isPalindrome(String s) {
+        int i = 0;
+        int j = s.length() - 1;
+        while (i < j) {
+            if (s.charAt(i++) != s.charAt(j--)) {
+                return false;
+            }
+        }
+        return true;
+    }
+}
+```
diff --git a/2019.01.23-leetcode131/marguerite.md b/2019.01.23-leetcode131/marguerite.md
new file mode 100644
index 000000000..3b5bf3be9
--- /dev/null
+++ b/2019.01.23-leetcode131/marguerite.md
@@ -0,0 +1,37 @@
+```
+public class Solution {
+    List> res=new ArrayList<>();
+    public List> partition(String s) {
+        DFS(s,new ArrayList());
+        return res;
+    }
+    private void DFS(String s,List list){
+		if(s.length()<1){
+			res.add(new ArrayList<>(list));
+			return;
+		}
+		for(int i=1;i<=s.length();i++){
+			String str=s.substring(0, i);
+			if(this.isPalindrom(str)){
+				list.add(str);
+				DFS(s.substring(i),list);
+				list.remove(list.size()-1);
+			}else{
+				continue;
+			}
+		}
+	}
+	private  boolean isPalindrom(String s){
+		
+		int p1=0;
+		int p2=s.length()-1;
+		int len=(s.length()+1)/2;
+		for(int i=0;i> partition(String s) {
+        List> res = new ArrayList<>();
+        if (s == null || s.length() == 0) {
+            return res;
+        }
+        find(res, new ArrayList(), s);
+        return res;
+    }
+    private  void find(List> res, ArrayList list, String s) {
+        if (s.length() == 0) {
+            res.add(new ArrayList(list));
+            return;
+        }
+        for (int i = 1; i <=s.length() ; i++) {
+            String temp = s.substring(0, i);
+            if (IsPalindrome(temp)) {
+                list.add(temp);
+                find(res,list,s.substring(i));
+                list.remove(list.size() - 1);
+            }
+        }
+
+    }
+    private  boolean IsPalindrome(String temp) {
+        int left=0;int right=temp.length()-1;
+        while (left < right) {
+            if (temp.charAt(left) != temp.charAt(right)) {
+                return false;
+            }else{
+                left++;
+                right--;
+            }
+        }
+        return true;
+    }
+}
diff --git "a/2019.01.23-leetcode131/\345\210\206\345\211\262\345\233\236\346\226\207\344\270\262" "b/2019.01.23-leetcode131/\345\210\206\345\211\262\345\233\236\346\226\207\344\270\262"
new file mode 100644
index 000000000..942590ce1
--- /dev/null
+++ "b/2019.01.23-leetcode131/\345\210\206\345\211\262\345\233\236\346\226\207\344\270\262"
@@ -0,0 +1,12 @@
+给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
+
+返回 s 所有可能的分割方案。
+
+示例:
+
+输入: "aab"
+输出:
+[
+  ["aa","b"],
+  ["a","a","b"]
+]
diff --git a/2019.01.24-leetcode37/Ostrichcrab.md b/2019.01.24-leetcode37/Ostrichcrab.md
new file mode 100644
index 000000000..e141b76c2
--- /dev/null
+++ b/2019.01.24-leetcode37/Ostrichcrab.md
@@ -0,0 +1,87 @@
+```
+class Solution {
+public:
+    void solveSudoku(vector > &board) {
+        solve(board, 0);
+    }
+    bool solve(vector > &board, int position)
+    {
+        if(position == 81)
+            return true;
+
+        int row = position / 9;
+        int col = position % 9;
+        if(board[row][col] == '.')
+        {
+            for(int i = 1; i <= 9; i ++)
+            {//try each digit
+                board[row][col] = i + '0';
+                if(check(board, position))
+                    if(solve(board, position + 1))
+                    //only return valid filling
+                        return true;
+                board[row][col] = '.';
+            }
+        }
+        else
+        {
+            if(solve(board, position + 1))
+            //only return valid filling
+                return true;
+        }
+        return false;
+    }
+    bool check(vector > &board, int position)
+    {
+        int row = position / 9;
+        int col = position % 9;
+        int gid;
+        if(row >= 0 && row <= 2)
+        {
+            if(col >= 0 && col <= 2)
+                gid = 0;
+            else if(col >= 3 && col <= 5)
+                gid = 1;
+            else
+                gid = 2;
+        }
+        else if(row >= 3 && row <= 5)
+        {
+            if(col >= 0 && col <= 2)
+                gid = 3;
+            else if(col >= 3 && col <= 5)
+                gid = 4;
+            else
+                gid = 5;
+        }
+        else
+        {
+            if(col >= 0 && col <= 2)
+                gid = 6;
+            else if(col >= 3 && col <= 5)
+                gid = 7;
+            else
+                gid = 8;
+        }
+
+        //check row, col, subgrid
+        for(int i = 0; i < 9; i ++)
+        {
+            //check row
+            if(i != col && board[row][i] == board[row][col])
+                return false;
+            
+            //check col
+            if(i != row && board[i][col] == board[row][col])
+                return false;
+            
+            //check subgrid
+            int r = gid/3*3+i/3;
+            int c = gid%3*3+i%3;
+            if((r != row || c != col) && board[r][c] == board[row][col])
+                return false;
+        }
+        return true;
+    }
+};
+```
diff --git a/2019.01.24-leetcode37/TheRocket.md b/2019.01.24-leetcode37/TheRocket.md
new file mode 100644
index 000000000..498154275
--- /dev/null
+++ b/2019.01.24-leetcode37/TheRocket.md
@@ -0,0 +1,59 @@
+```java
+class Solution {
+    public void solveSudoku(char[][] board) {
+        // 记录某行的某位数字是否已经被摆放
+        boolean[][] row = new boolean[9][9];
+        // 记录某列的某位数字是否已经被摆放
+        boolean[][] col = new boolean[9][9];
+        // 记录 3x3 宫格内的某位数字是否已经被摆放
+        boolean[][] block = new boolean[9][9];
+        for (int i = 0; i < 9; ++i) {
+            for (int j = 0; j < 9; ++j) {
+                if (board[i][j] != '.') {
+                    int num = board[i][j] - '1';
+                    row[i][num] = true;
+                    col[j][num] = true;
+                    // 化二维的 3x3 为一维的 0~8
+                    block[i / 3 * 3 + j / 3][num] = true;
+                }
+            }
+        }
+        dfs(board, 0, 0, row, col, block);
+    }
+
+    private boolean dfs(char[][] board, int i, int j, boolean[][] row, boolean[][] col, boolean[][] block) {
+        while (board[i][j] != '.') {
+            if (++j == 9) {
+                ++i;
+                j = 0;
+            }
+            if (i == 9) {
+                return true;
+            }
+
+        }
+        // 化二维的 3x3 为一维的 0~8
+        int blockIndex = i / 3 * 3 + j / 3;
+        for (int k = 0; k < 9; ++k) {
+            if (!row[i][k] && !col[j][k] && !block[blockIndex][k]) {
+                // 设置访问标志
+                row[i][k] = true;
+                col[j][k] = true;
+                block[blockIndex][k] = true;
+                // 改变当前值
+                board[i][j] = (char) ('1' + k);
+                // 进入下一层,成功则直接返回
+                if (dfs(board, i, j, row, col, block)) {
+                    return true;
+                }
+                // 恢复
+                row[i][k] = false;
+                col[j][k] = false;
+                block[blockIndex][k] = false;
+                board[i][j] = '.';
+            }
+        }
+        return false;
+    }
+}
+```
diff --git "a/2019.01.24-leetcode37/\345\210\230\346\266\246\346\263\275(capture).md" "b/2019.01.24-leetcode37/\345\210\230\346\266\246\346\263\275(capture).md"
new file mode 100644
index 000000000..6a439f5c8
--- /dev/null
+++ "b/2019.01.24-leetcode37/\345\210\230\346\266\246\346\263\275(capture).md"
@@ -0,0 +1,87 @@
+```java
+    public void solveSudoku(char[][] board) {
+
+        int[] next = findNext(0, 0, board);
+        huisu(next[0],next[1],board);
+
+    }
+
+    public boolean huisu(int i, int j, char[][] board){
+
+        System.out.println(i+" "+j);
+
+        int[] other = findOther(i, j, board);
+
+        for (int m=1;m> solveNQueens(int n) {
+        vector> res;
+        vector nQueens(n,string(n,'.'));
+        solveNQueens(res,nQueens,0,n);
+        return res;
+    }
+    void solveNQueens(vector>&res,vector& nQueens, int row, int &n){
+        if(row==n){
+            res.push_back(nQueens);
+            return ;
+        }
+        for(int col = 0; col != n; col++)
+            if(isValid(nQueens, row, col, n)){
+                nQueens[row][col]='Q';
+                solveNQueens(res,nQueens,row+1,n);
+                nQueens[row][col]='.';
+            }
+    }
+    bool isValid(vector& nQueens, int row, int col, int &n){
+    for(int i = 0; i != row; i++)
+        if(nQueens[i][col]=='Q') return false;
+        for(int i = row -1,j=col-1; i>=0&&j>=0; i--,j--)
+            if(nQueens[i][j]=='Q') return false;
+        for(int i = row-1,j=col+1;i>=0&&j> solveNQueens(int n) {
+        List> res = new ArrayList<>();
+        char[][] cs = new char[n][n];
+        for (int i = 0; i < cs.length; ++i) {
+            Arrays.fill(cs[i], '.');
+        }
+        dfs(cs, 0, res);
+        return res;
+    }
+
+    private void dfs(char[][] cs, int r, List> res) {
+        int n = cs.length;
+        if (r == n) {
+            List list = new ArrayList<>(n);
+            for (int i = 0; i < n; ++i) {
+                list.add(new String(cs[i]));
+            }
+            res.add(list);
+            return;
+        }
+        for (int i = 0; i < n; ++i) {
+            if (isValid(cs, r, i)) {
+                cs[r][i] = 'Q';
+                dfs(cs, r + 1, res);
+                cs[r][i] = '.';
+            }
+        }
+    }
+
+    private boolean isValid(char[][] cs, int r, int c) {
+        int j = c;
+        for (int i = r - 1; i >= 0; --i) {
+            if (cs[i][j] == 'Q') {
+                return false;
+            }
+        }
+        j = c - 1;
+        for (int i = r - 1; i >= 0 && j >= 0; --i) {
+            if (cs[i][j--] == 'Q') {
+                return false;
+            }
+        }
+        j = c + 1;
+        for (int i = r - 1; i >= 0 && j < cs.length; --i) {
+            if (cs[i][j++] == 'Q') {
+                return false;
+            }
+        }
+        return true;
+    }
+}
+```
diff --git a/2019.01.25-leetcode51/sourcema.md b/2019.01.25-leetcode51/sourcema.md
new file mode 100644
index 000000000..b9c23c97b
--- /dev/null
+++ b/2019.01.25-leetcode51/sourcema.md
@@ -0,0 +1,41 @@
+# LeetCode 51
+    class Solution {
+    List> result = new ArrayList<>();
+    StringBuilder point = new StringBuilder();
+    HashSet col = new HashSet<>();
+    HashSet pie = new HashSet<>();
+    HashSet na = new HashSet<>();
+
+    public List> solveNQueens(int n) {
+        for (int i = 0; i < n; i++) point.append('.');
+        dfs(n, new ArrayList());
+        return result;
+    }
+
+     void dfs(int n, List list) {
+        if (list.size() == n) {
+            List line = new ArrayList<>();
+            for (int i = 0; i < n; i++) {
+                point.replace(list.get(i), list.get(i) + 1, "Q");
+                line.add(point.toString());
+                point.replace(list.get(i), list.get(i) + 1, ".");
+            }
+            result.add(line);
+            return;
+        }
+        for (int i = 0; i < n; i++) {
+            if (col.contains(i)|| pie.contains(list.size()-i) || na.contains(list.size()+i)) {
+                continue;
+            }
+            col.add(i);
+            pie.add(list.size() - i);
+            na.add(list.size() + i);
+            list.add(i);
+            dfs(n, list);
+            list.remove(list.size()-1);
+            col.remove(i);
+            pie.remove(list.size() - i);
+            na.remove(list.size() + i);
+        }
+     }
+}
diff --git "a/2019.01.25-leetcode51/\346\243\225\346\246\210\346\240\221.md" "b/2019.01.25-leetcode51/\346\243\225\346\246\210\346\240\221.md"
new file mode 100644
index 000000000..d50d2aa5f
--- /dev/null
+++ "b/2019.01.25-leetcode51/\346\243\225\346\246\210\346\240\221.md"
@@ -0,0 +1,51 @@
+```
+class Solution {
+    public List> solveNQueens(int n) {
+        List> res = new ArrayList<>();
+        char[][] board = new char[n][n];
+        for(int i=0;i> res){
+    	if(colIndex==board.length){
+    		res.add(construct(board));
+    		return;
+    	}
+    	
+    	for(int i=0;i construct(char[][] board){
+    	List res = new LinkedList<>();
+    	for(int i=0;i dp(n+3);
+        dp[0]=0;
+        dp[1]=1;
+        dp[2]=2;
+        for(int i = 3; i <= n; i++)
+        {
+            dp[i]=dp[i-1]+dp[i-2];
+        }
+        return dp[n];
+    }
+};
+```
diff --git a/2019.01.26-leetcode70/TheRocket.md b/2019.01.26-leetcode70/TheRocket.md
new file mode 100644
index 000000000..3b0e5e6a4
--- /dev/null
+++ b/2019.01.26-leetcode70/TheRocket.md
@@ -0,0 +1,17 @@
+```java
+class Solution {
+    public int climbStairs(int n) {
+        if (n <= 2) {
+            return n;
+        }
+        int a = 1, b = 2;
+        int res = 0;
+        for (int i = 3; i <= n; ++i) {
+            res = a + b;
+            a = b;
+            b = res;
+        }
+        return res;
+    }
+}
+```
diff --git a/2019.01.26-leetcode70/sourcema.md b/2019.01.26-leetcode70/sourcema.md
new file mode 100644
index 000000000..32fa77388
--- /dev/null
+++ b/2019.01.26-leetcode70/sourcema.md
@@ -0,0 +1,20 @@
+# LeetCode 70
+    class Solution {
+    public int climbStairs(int n) {
+         if (n == 1) {
+            return 1;
+        }
+        if (n == 2) {
+            return 2;
+        }
+        int one=1;
+        int two=2;
+        int res=0;
+        for (int i = 3; i <=n ; i++) {
+            res=one+two;
+            one=two;
+            two=res;
+        }
+        return res;
+    }
+}
diff --git "a/2019.01.26-leetcode70/\346\243\225\346\246\210\346\240\221.md" "b/2019.01.26-leetcode70/\346\243\225\346\246\210\346\240\221.md"
new file mode 100644
index 000000000..307465304
--- /dev/null
+++ "b/2019.01.26-leetcode70/\346\243\225\346\246\210\346\240\221.md"
@@ -0,0 +1,19 @@
+```
+class Solution {
+    
+    Map dp = new HashMap<>();
+    
+    public int climbStairs(int n) {
+       if(n<0)
+			return 0;
+		if(n==0)
+			return 1;
+		if(dp.containsKey(n))
+			return dp.get(n);
+		int steps = climbStairs(n-1)+climbStairs(n-2);
+		dp.put(n, steps);
+		return steps;
+    }
+    
+}
+```
diff --git "a/2019.01.26-leetcode70/\347\210\254\346\245\274\346\242\257" "b/2019.01.26-leetcode70/\347\210\254\346\245\274\346\242\257"
new file mode 100644
index 000000000..e0ec4ddbe
--- /dev/null
+++ "b/2019.01.26-leetcode70/\347\210\254\346\245\274\346\242\257"
@@ -0,0 +1,21 @@
+假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
+
+每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
+
+注意:给定 n 是一个正整数。
+
+示例 1:
+
+输入: 2
+输出: 2
+解释: 有两种方法可以爬到楼顶。
+1.  1 阶 + 1 阶
+2.  2 阶
+示例 2:
+
+输入: 3
+输出: 3
+解释: 有三种方法可以爬到楼顶。
+1.  1 阶 + 1 阶 + 1 阶
+2.  1 阶 + 2 阶
+3.  2 阶 + 1 阶
diff --git a/2019.01.27-leetcode198/Ostrichcrab.md b/2019.01.27-leetcode198/Ostrichcrab.md
new file mode 100644
index 000000000..cbd8f80a0
--- /dev/null
+++ b/2019.01.27-leetcode198/Ostrichcrab.md
@@ -0,0 +1,19 @@
+```
+//dp[i]:=走到第i家,获得的最大收入
+class Solution {
+public:
+    int rob(vector& a) {
+        int n = a.size();
+        if(n==0) return 0;
+        int dp[n+2];
+        dp[0]=a[0];
+        if(n==1) return a[0];
+        dp[1]=max(a[0],a[1]);
+        for(int i = 2; i < n; i++)
+        {
+            dp[i]=max(dp[i-2]+a[i],dp[i-1]);
+        }
+        return dp[n-1];
+    }
+};
+```
diff --git a/2019.01.27-leetcode198/TheRocket.md b/2019.01.27-leetcode198/TheRocket.md
new file mode 100644
index 000000000..9afde4fb2
--- /dev/null
+++ b/2019.01.27-leetcode198/TheRocket.md
@@ -0,0 +1,15 @@
+```java
+class Solution {
+    public int rob(int[] nums) {
+        int pre2 = 0;
+        int pre1 = 0;
+        int cur = 0;
+        for (int num : nums) {
+            cur = Math.max(pre2 + num, pre1);
+            pre2 = pre1;
+            pre1 = cur;
+        }
+        return cur;
+    }
+}
+```
diff --git a/2019.01.27-leetcode198/sourcema.md b/2019.01.27-leetcode198/sourcema.md
new file mode 100644
index 000000000..af86b82d1
--- /dev/null
+++ b/2019.01.27-leetcode198/sourcema.md
@@ -0,0 +1,18 @@
+# leetcode 198
+    class Solution {
+    public int rob(int[] nums) {
+        if(nums==null||nums.length==0){
+            return 0;
+        }
+        if(nums.length==1){
+            return nums[0];
+        }
+        int[] dp=new int[nums.length];
+        dp[0]=nums[0];
+        dp[1]=Math.max(dp[0],nums[1]);
+        for(int i=2;inums[1]?nums[0]:nums[1];
+    	}
+    	int[] dp = new int[nums.length];
+    	dp[0] = nums[0];
+    	dp[1] = nums[0]>nums[1]?nums[0]:nums[1];
+    	for(int i=2;i& nums) {
+        int ans = -1;
+        vector a;
+        if(nums.size()==0) return 0;
+        if(nums.size()==1) return nums[0];
+        for(int i = 1; i < nums.size(); i++)
+        {
+            a.push_back(nums[i]);
+        }
+        nums.pop_back();
+        ans = robber(a)>robber(nums)?robber(a):robber(nums);
+        return ans;
+    }
+    int robber(vector& a) {
+        int n = a.size();
+        if(n==0) return 0;
+        int dp[n+2];
+        dp[0]=a[0];
+        if(n==1) return a[0];
+        dp[1]=max(a[0],a[1]);
+        for(int i = 2; i < n; i++)
+        {
+            dp[i]=max(dp[i-2]+a[i],dp[i-1]);
+        }
+        return dp[n-1];
+    }
+};
+```
diff --git a/2019.01.28-leetcode213/TheRocket.md b/2019.01.28-leetcode213/TheRocket.md
new file mode 100644
index 000000000..1420896b5
--- /dev/null
+++ b/2019.01.28-leetcode213/TheRocket.md
@@ -0,0 +1,25 @@
+```java
+class Solution {
+    public int rob(int[] nums) {
+        if (nums == null || nums.length == 0) {
+            return 0;
+        }
+        if (nums.length == 1) {
+            return nums[0];
+        }
+        return Math.max(rob(nums, 0, nums.length - 2), rob(nums, 1, nums.length - 1));
+    }
+
+    public int rob(int[] nums, int begin, int end) {
+        int pre2 = 0;
+        int pre1 = 0;
+        int cur = 0;
+        for (int i = begin; i <= end; ++i) {
+            cur = Math.max(pre2 + nums[i], pre1);
+            pre2 = pre1;
+            pre1 = cur;
+        }
+        return cur;
+    }
+}
+```
diff --git a/2019.01.28-leetcode213/sourcema.md b/2019.01.28-leetcode213/sourcema.md
new file mode 100644
index 000000000..0a53fdf8e
--- /dev/null
+++ b/2019.01.28-leetcode213/sourcema.md
@@ -0,0 +1,25 @@
+# leetcode 213
+    class Solution {
+    public int rob(int[] nums) {
+         if(nums==null||nums.length==0){
+            return 0;
+        }
+        if(nums.length==1){
+            return nums[0];
+        }
+        if(nums.length==2){
+            return Math.max(nums[0],nums[1]);
+        }
+        int[] dp1=new int[nums.length];
+        int[] dp2=new int[nums.length-1];
+        dp1[1]=nums[1];
+        dp2[0]=nums[0];dp2[1]=Math.max(dp2[0],nums[1]);
+        for(int i=2;i>& grid) {
+        int n = grid.size();
+        int m = grid[0].size();
+        int dp[n+1][m+1];
+        dp[0][0]=grid[0][0];
+        for(int i = 1; i < n; i++) dp[i][0]=grid[i][0]+dp[i-1][0];
+        for(int i = 1; i < m; i++) dp[0][i]=grid[0][i]+dp[0][i-1];
+        for(int i = 1; i < n; i++){
+            for(int j = 1; j < m; j++){
+                dp[i][j] = min(dp[i-1][j]+grid[i][j],dp[i][j-1]+grid[i][j]);
+            }
+        }
+        return dp[n-1][m-1];
+    }
+};
+```
diff --git a/2019.01.29-leetcode64/TheRocket.md b/2019.01.29-leetcode64/TheRocket.md
new file mode 100644
index 000000000..fd315da7b
--- /dev/null
+++ b/2019.01.29-leetcode64/TheRocket.md
@@ -0,0 +1,22 @@
+```java
+class Solution {
+    public int minPathSum(int[][] grid) {
+        int m = grid.length;
+        int n = grid[0].length;
+        int[][] dp = new int[m][n];
+        dp[0][0] = grid[0][0];
+        for (int i = 1; i < m; ++i) {
+            dp[i][0] = dp[i - 1][0] + grid[i][0];
+        }
+        for (int i = 1; i < n; ++i) {
+            dp[0][i] = dp[0][i - 1] + grid[0][i];
+        }
+        for (int i = 1; i < m; ++i) {
+            for (int j = 1; j < n; ++j) {
+                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
+            }
+        }
+        return dp[m - 1][n - 1];
+    }
+}
+```
diff --git a/2019.01.29-leetcode64/sourcema.md b/2019.01.29-leetcode64/sourcema.md
new file mode 100644
index 000000000..7be7fe039
--- /dev/null
+++ b/2019.01.29-leetcode64/sourcema.md
@@ -0,0 +1,22 @@
+# leetcode 64
+    class Solution {
+    public int minPathSum(int[][] grid) {//动态规划模板题,直接手撸
+        if(grid==null||grid.length==0||grid[0].length==0){
+            return 0;
+        }
+        int[][] dp=new int[grid.length][grid[0].length];
+        dp[0][0]=grid[0][0];
+        for(int i=1;i 向右 -> 向下
+2. 向右 -> 向下 -> 向右
+3. 向下 -> 向右 -> 向右
+示例 2:
+
+输入: m = 7, n = 3
+输出: 28
diff --git "a/2019.01.30-leetcode62/\346\243\225\346\246\210\346\240\221.md" "b/2019.01.30-leetcode62/\346\243\225\346\246\210\346\240\221.md"
new file mode 100644
index 000000000..634d2c420
--- /dev/null
+++ "b/2019.01.30-leetcode62/\346\243\225\346\246\210\346\240\221.md"
@@ -0,0 +1,23 @@
+```
+class Solution {
+    public int uniquePaths(int m, int n) {
+        int[][] map = new int[m][n];
+        for(int i=0;i sum;
+    NumArray(vector nums) {
+        sum.push_back(0);
+        for(int i = 0; i < nums.size(); i++)
+            sum.push_back(nums[i]+sum.back());
+    }
+    
+    int sumRange(int i, int j) {
+        return sum[j+1]-sum[i];
+    }
+};
+
+/**
+ * Your NumArray object will be instantiated and called as such:
+ * NumArray obj = new NumArray(nums);
+ * int param_1 = obj.sumRange(i,j);
+ */
+ ```
diff --git a/2019.01.31-leetcode303/TheRocket.md b/2019.01.31-leetcode303/TheRocket.md
new file mode 100644
index 000000000..684bc79f4
--- /dev/null
+++ b/2019.01.31-leetcode303/TheRocket.md
@@ -0,0 +1,22 @@
+```java
+class NumArray {
+    private int[] sums;
+
+    public NumArray(int[] nums) {
+        sums = new int[nums.length + 1];
+        for (int i = 0; i < nums.length; ++i) {
+            sums[i + 1] = sums[i] + nums[i];
+        }
+    }
+
+    public int sumRange(int i, int j) {
+        return sums[j + 1] - sums[i];
+    }
+}
+
+/**
+ * Your NumArray object will be instantiated and called as such:
+ * NumArray obj = new NumArray(nums);
+ * int param_1 = obj.sumRange(i,j);
+ */
+ ```
diff --git a/2019.01.31-leetcode303/sourcema.md b/2019.01.31-leetcode303/sourcema.md
new file mode 100644
index 000000000..85b17ca22
--- /dev/null
+++ b/2019.01.31-leetcode303/sourcema.md
@@ -0,0 +1,28 @@
+# leetcode 303
+    class NumArray {
+    int[] dp;
+    public NumArray(int[] nums) {
+        if(nums==null||nums.length==0){//test
+            return;
+        }
+        dp=new int[nums.length];
+        dp[0]=nums[0];
+        for(int i=1;i 1
+sumRange(2, 5) -> -1
+sumRange(0, 5) -> -3
+说明:
+
+你可以假设数组不可变。
+会多次调用 sumRange 方法。
diff --git "a/2019.01.31-leetcode303/\346\243\225\346\246\210\346\240\221.md" "b/2019.01.31-leetcode303/\346\243\225\346\246\210\346\240\221.md"
new file mode 100644
index 000000000..2ef03d955
--- /dev/null
+++ "b/2019.01.31-leetcode303/\346\243\225\346\246\210\346\240\221.md"
@@ -0,0 +1,33 @@
+```
+package day;
+
+import java.util.HashMap;
+import java.util.Map;
+
+
+public class NumArray {
+	int[] nums;
+	
+    public NumArray(int[] nums) {
+    	for(int i=1;i& A) {
+        if(A.size()<3) return 0;
+        int now = 0;
+        int ans = 0;
+        for(int i = 2; i < A.size(); i++){
+            if(A[i]-A[i-1] == A[i-1]-A[i-2]) now++;
+            else now = 0;
+            ans+=now;
+        }
+        
+       return ans; 
+    }
+};
+```
diff --git a/2019.02.01-leetcode413/TheRocket.md b/2019.02.01-leetcode413/TheRocket.md
new file mode 100644
index 000000000..240627a95
--- /dev/null
+++ b/2019.02.01-leetcode413/TheRocket.md
@@ -0,0 +1,19 @@
+```java
+class Solution {
+    public int numberOfArithmeticSlices(int[] A) {
+        if (A == null || A.length < 3) {
+            return 0;
+        }
+        int res = 0;
+        int cur = 0;
+        for (int i = 2; i < A.length; ++i) {
+            if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
+                res += ++cur;
+            } else {
+                cur = 0;
+            }
+        }
+        return res;
+    }
+}
+```
diff --git a/2019.02.01-leetcode413/sourcema.md b/2019.02.01-leetcode413/sourcema.md
new file mode 100644
index 000000000..df0c2f983
--- /dev/null
+++ b/2019.02.01-leetcode413/sourcema.md
@@ -0,0 +1,26 @@
+# leetcode 413
+    class Solution {
+    public int numberOfArithmeticSlices(int[] A) {
+        if(A==null||A.length==0){
+            return 0;
+        }
+        int res=0;
+        for(int i=0;i=2&&isArithmetic(A,i,j)){
+                    res+=1;
+                }
+            }
+        }
+        return res;
+    }
+    public boolean isArithmetic(int[] arr,int i,int j){
+        int d=arr[i+1]-arr[i];
+        for(int k=i+1;k> 1;
+        for (int i = 1; i <= half; ++i) {
+            for (int j = i; i + j <= n; ++j) {
+                dp[i + j] = Math.max(dp[i + j], Math.max(i, dp[i]) * Math.max(j, dp[j]));
+            }
+        }
+        return dp[n];
+    }
+}
+```
diff --git "a/2019.02.02-leetcode343/\346\225\264\346\225\260\346\213\206\345\210\206" "b/2019.02.02-leetcode343/\346\225\264\346\225\260\346\213\206\345\210\206"
new file mode 100644
index 000000000..00f187992
--- /dev/null
+++ "b/2019.02.02-leetcode343/\346\225\264\346\225\260\346\213\206\345\210\206"
@@ -0,0 +1,13 @@
+给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
+
+示例 1:
+
+输入: 2
+输出: 1
+解释: 2 = 1 + 1, 1 × 1 = 1。
+示例 2:
+
+输入: 10
+输出: 36
+解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
+说明: 你可以假设 n 不小于 2 且不大于 58。
diff --git "a/2019.02.02-leetcode343/\346\243\225\346\246\210\346\240\221.md" "b/2019.02.02-leetcode343/\346\243\225\346\246\210\346\240\221.md"
new file mode 100644
index 000000000..6be93f1ff
--- /dev/null
+++ "b/2019.02.02-leetcode343/\346\243\225\346\246\210\346\240\221.md"
@@ -0,0 +1,32 @@
+```
+public class Integer_Break {
+	/*
+    public static int integerBreak(int n) {
+        if(n==2)	return 1;
+        if(n==3)	return 2;
+        int product = 1;
+        while(n>4){
+        	System.out.println(product);
+        	product *=3;
+        	n -= 3;
+        }
+        product *= n;
+    	return product;
+    }
+    */
+	
+	public static int integerBreak(int n){
+		int[] dp = new int[n+1];
+		dp[1] = 1;
+		for(int i=2;i<=n;i++){
+			for(int j=1;j<=i/2;j++){
+				dp[i] = Math.max(dp[i], (Math.max(j, dp[j])*(Math.max(i-j, dp[i-j]))));
+			}
+		}
+		return dp[n];
+	}
+    public static void main(String[] args) {
+		System.out.println(integerBreak(10));
+	}
+}
+```
diff --git a/2019.02.03-leetocde279/Ostrichcrab.md b/2019.02.03-leetocde279/Ostrichcrab.md
new file mode 100644
index 000000000..16563e006
--- /dev/null
+++ b/2019.02.03-leetocde279/Ostrichcrab.md
@@ -0,0 +1,17 @@
+```
+class Solution {
+public:
+    int numSquares(int n) {
+        vector dp;
+        dp.push_back(0);
+        for(int i = 1; i <= n; i++) dp.push_back(i);
+        // for(int i = 0; i <= n; i++) cout<=0){
+    			min = Math.min(min, dp[i-j*j]+1);
+    			++j;
+    		}
+    		dp[i] = min;
+    	}
+    	return dp[n];
+    }
+}
+```
diff --git a/2019.02.09-leetcode91/TheRocket.md b/2019.02.09-leetcode91/TheRocket.md
new file mode 100644
index 000000000..c66979187
--- /dev/null
+++ b/2019.02.09-leetcode91/TheRocket.md
@@ -0,0 +1,32 @@
+```java
+class Solution {
+    public int numDecodings(String s) {
+        if (s == null || s.length() == 0 || s.charAt(0) == '0') {
+            return 0;
+        }
+        int pre2 = 1;
+        int pre1 = 1;
+        int res = 1;
+        char prec = s.charAt(0);
+        for (int i = 1; i < s.length(); ++i) {
+            char c = s.charAt(i);
+            if (c == '0') {
+                if ((prec == '1' || prec == '2')) {
+                    res = pre2;
+                } else {
+                    return 0;
+                }
+            } else {
+                res = pre1;
+                if (prec == '1' || (prec == '2' && c <= '6')) {
+                    res += pre2;
+                }
+            }
+            pre2 = pre1;
+            pre1 = res;
+            prec = c;
+        }
+        return res;
+    }
+}
+```
diff --git "a/2019.02.09-leetcode91/\350\247\243\347\240\201\346\226\271\346\263\225" "b/2019.02.09-leetcode91/\350\247\243\347\240\201\346\226\271\346\263\225"
new file mode 100644
index 000000000..c7a285987
--- /dev/null
+++ "b/2019.02.09-leetcode91/\350\247\243\347\240\201\346\226\271\346\263\225"
@@ -0,0 +1,18 @@
+一条包含字母 A-Z 的消息通过以下方式进行了编码:
+
+'A' -> 1
+'B' -> 2
+...
+'Z' -> 26
+给定一个只包含数字的非空字符串,请计算解码方法的总数。
+
+示例 1:
+
+输入: "12"
+输出: 2
+解释: 它可以解码为 "AB"(1 2)或者 "L"(12)。
+示例 2:
+
+输入: "226"
+输出: 3
+解释: 它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。
diff --git a/2019.02.10-leetcode300/TheRocket.md b/2019.02.10-leetcode300/TheRocket.md
new file mode 100644
index 000000000..5c98e2871
--- /dev/null
+++ b/2019.02.10-leetcode300/TheRocket.md
@@ -0,0 +1,19 @@
+```java
+class Solution {
+    public int lengthOfLIS(int[] nums) {
+        int[] dp = new int[nums.length];
+        int len = 0;
+        for (int num : nums) {
+            int i = Arrays.binarySearch(dp, 0, len, num);
+            if (i < 0) {
+                i = -(i + 1);
+            }
+            dp[i] = num;
+            if (i == len) {
+                ++len;
+            }
+        }
+        return len;
+    }
+}
+```
diff --git "a/2019.02.10-leetcode300/\346\234\200\351\225\277\344\270\212\345\215\207\345\255\220\345\272\217\345\210\227" "b/2019.02.10-leetcode300/\346\234\200\351\225\277\344\270\212\345\215\207\345\255\220\345\272\217\345\210\227"
new file mode 100644
index 000000000..c258ed444
--- /dev/null
+++ "b/2019.02.10-leetcode300/\346\234\200\351\225\277\344\270\212\345\215\207\345\255\220\345\272\217\345\210\227"
@@ -0,0 +1,12 @@
+给定一个无序的整数数组,找到其中最长上升子序列的长度。
+
+示例:
+
+输入: [10,9,2,5,3,7,101,18]
+输出: 4 
+解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
+说明:
+
+可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
+你算法的时间复杂度应该为 O(n2) 。
+进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?
diff --git a/2019.02.11-leetcode646/TheRocket.md b/2019.02.11-leetcode646/TheRocket.md
new file mode 100644
index 000000000..03e81c239
--- /dev/null
+++ b/2019.02.11-leetcode646/TheRocket.md
@@ -0,0 +1,19 @@
+```java
+class Solution {
+    public int findLongestChain(int[][] pairs) {
+        if (pairs == null || pairs.length == 0) {
+            return 0;
+        }
+        Arrays.sort(pairs, Comparator.comparingInt(o -> o[1]));
+        int res = 1;
+        int pre = pairs[0][1];
+        for (int[] pair : pairs) {
+            if (pair[0] > pre) {
+                ++res;
+                pre = pair[1];
+            }
+        }
+        return res;
+    }
+}
+```
diff --git a/2019.02.11-leetcode646/jackykun2012.md b/2019.02.11-leetcode646/jackykun2012.md
new file mode 100644
index 000000000..03e81c239
--- /dev/null
+++ b/2019.02.11-leetcode646/jackykun2012.md
@@ -0,0 +1,19 @@
+```java
+class Solution {
+    public int findLongestChain(int[][] pairs) {
+        if (pairs == null || pairs.length == 0) {
+            return 0;
+        }
+        Arrays.sort(pairs, Comparator.comparingInt(o -> o[1]));
+        int res = 1;
+        int pre = pairs[0][1];
+        for (int[] pair : pairs) {
+            if (pair[0] > pre) {
+                ++res;
+                pre = pair[1];
+            }
+        }
+        return res;
+    }
+}
+```
diff --git "a/2019.02.11-leetcode646/\346\234\200\351\225\277\346\225\260\345\257\271\351\223\276" "b/2019.02.11-leetcode646/\346\234\200\351\225\277\346\225\260\345\257\271\351\223\276"
new file mode 100644
index 000000000..9e894d454
--- /dev/null
+++ "b/2019.02.11-leetcode646/\346\234\200\351\225\277\346\225\260\345\257\271\351\223\276"
@@ -0,0 +1,14 @@
+给出 n 个数对。 在每一个数对中,第一个数字总是比第二个数字小。
+
+现在,我们定义一种跟随关系,当且仅当 b < c 时,数对(c, d) 才可以跟在 (a, b) 后面。我们用这种形式来构造一个数对链。
+
+给定一个对数集合,找出能够形成的最长数对链的长度。你不需要用到所有的数对,你可以以任何顺序选择其中的一些数对来构造。
+
+示例 :
+
+输入: [[1,2], [2,3], [3,4]]
+输出: 2
+解释: 最长的数对链是 [1,2] -> [3,4]
+注意:
+
+给出数对的个数在 [1, 1000] 范围内。
diff --git a/2019.02.12-leetcode376/TheRocket.md b/2019.02.12-leetcode376/TheRocket.md
new file mode 100644
index 000000000..d4e4b3186
--- /dev/null
+++ b/2019.02.12-leetcode376/TheRocket.md
@@ -0,0 +1,19 @@
+```java
+class Solution {
+    public int wiggleMaxLength(int[] nums) {
+        if (nums.length < 2) {
+            return nums.length;
+        }
+        int up = 1;
+        int down = 1;
+        for (int i = 1; i < nums.length; ++i) {
+            if (nums[i] > nums[i - 1]) {
+                up = down + 1;
+            } else if (nums[i] < nums[i - 1]) {
+                down = up + 1;
+            }
+        }
+        return Math.max(up, down);
+    }
+}
+```
diff --git "a/2019.02.12-leetcode376/\346\221\206\345\212\250\345\272\217\345\210\227" "b/2019.02.12-leetcode376/\346\221\206\345\212\250\345\272\217\345\210\227"
new file mode 100644
index 000000000..ad916a81f
--- /dev/null
+++ "b/2019.02.12-leetcode376/\346\221\206\345\212\250\345\272\217\345\210\227"
@@ -0,0 +1,22 @@
+如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。
+
+例如, [1,7,4,9,2,5] 是一个摆动序列,因为差值 (6,-3,5,-7,3) 是正负交替出现的。相反, [1,4,7,2,5] 和 [1,7,4,5,5] 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。
+
+给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。
+
+示例 1:
+
+输入: [1,7,4,9,2,5]
+输出: 6 
+解释: 整个序列均为摆动序列。
+示例 2:
+
+输入: [1,17,5,10,13,15,10,5,16,8]
+输出: 7
+解释: 这个序列包含几个长度为 7 摆动序列,其中一个可为[1,17,10,13,10,16,8]。
+示例 3:
+
+输入: [1,2,3,4,5,6,7,8,9]
+输出: 2
+进阶:
+你能否用 O(n) 时间复杂度完成此题?
diff --git a/2019.02.13-leetcode416/TheRocket.md b/2019.02.13-leetcode416/TheRocket.md
new file mode 100644
index 000000000..1b84d5128
--- /dev/null
+++ b/2019.02.13-leetcode416/TheRocket.md
@@ -0,0 +1,23 @@
+```java
+public boolean canPartition(int[] nums) {
+    int sum = 0;
+    for (int num : nums) {
+        sum += num;
+    }
+    if ((sum & 1) == 1) {
+        return false;
+    }
+    sum /= 2;
+    boolean[] dp = new boolean[sum + 1];
+    dp[0] = true;
+    for (int num : nums) {
+        for (int i = sum; i >= num; --i) {
+            dp[i] = dp[i] || dp[i - num];
+            if (dp[sum]) {
+                return true;
+            }
+        }
+    }
+    return false;
+}
+```
diff --git "a/2019.02.13-leetcode416/\345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\351\233\206" "b/2019.02.13-leetcode416/\345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\351\233\206"
new file mode 100644
index 000000000..bc8af3ce0
--- /dev/null
+++ "b/2019.02.13-leetcode416/\345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\351\233\206"
@@ -0,0 +1,22 @@
+给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
+
+注意:
+
+每个数组中的元素不会超过 100
+数组的大小不会超过 200
+示例 1:
+
+输入: [1, 5, 11, 5]
+
+输出: true
+
+解释: 数组可以分割成 [1, 5, 5] 和 [11].
+ 
+
+示例 2:
+
+输入: [1, 2, 3, 5]
+
+输出: false
+
+解释: 数组不能分割成两个元素和相等的子集.
diff --git a/2019.02.14-leetcode494/TheRocket.md b/2019.02.14-leetcode494/TheRocket.md
new file mode 100644
index 000000000..518289c25
--- /dev/null
+++ b/2019.02.14-leetcode494/TheRocket.md
@@ -0,0 +1,25 @@
+```java
+class Solution {
+    public int findTargetSumWays(int[] nums, int S) {
+        int sum = 0;
+        for (int num : nums) {
+            sum += num;
+        }
+        if (sum < S || ((S + sum) & 1) == 1) {
+            return 0;
+        }
+        return subsetSum(nums, (S + sum) >> 1);
+    }
+
+    private int subsetSum(int[] nums, int sum) {
+        int[] dp = new int[sum + 1];
+        dp[0] = 1;
+        for (int num : nums) {
+            for (int i = sum; i >= num; --i) {
+                dp[i] += dp[i - num];
+            }
+        }
+        return dp[sum];
+    }
+}
+```
diff --git "a/2019.02.14-leetcode494/\347\233\256\346\240\207\345\222\214" "b/2019.02.14-leetcode494/\347\233\256\346\240\207\345\222\214"
new file mode 100644
index 000000000..595a4d1ce
--- /dev/null
+++ "b/2019.02.14-leetcode494/\347\233\256\346\240\207\345\222\214"
@@ -0,0 +1,22 @@
+给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。
+
+返回可以使最终数组和为目标数 S 的所有添加符号的方法数。
+
+示例 1:
+
+输入: nums: [1, 1, 1, 1, 1], S: 3
+输出: 5
+解释: 
+
+-1+1+1+1+1 = 3
++1-1+1+1+1 = 3
++1+1-1+1+1 = 3
++1+1+1-1+1 = 3
++1+1+1+1-1 = 3
+
+一共有5种方法让最终目标和为3。
+注意:
+
+数组的长度不会超过20,并且数组中的值全为正数。
+初始的数组的和不会超过1000。
+保证返回的最终结果为32位整数。
diff --git a/2019.02.15-leetcode139/TheRocket.md b/2019.02.15-leetcode139/TheRocket.md
new file mode 100644
index 000000000..488c9ebf0
--- /dev/null
+++ b/2019.02.15-leetcode139/TheRocket.md
@@ -0,0 +1,18 @@
+```java
+class Solution {
+    public boolean wordBreak(String s, List wordDict) {
+        Set set = new HashSet<>(wordDict);
+        int n = s.length();
+        boolean[] dp = new boolean[n + 1];
+        dp[0] = true;
+        for (int i = 1; i <= n; ++i) {
+            for (int j = i; j >= 0; --j) {
+                if (dp[j] && set.contains(s.substring(j, i))) {
+                    dp[i] = true;
+                }
+            }
+        }
+        return dp[n];
+    }
+}
+```
diff --git "a/2019.02.15-leetcode139/\345\215\225\350\257\215\346\213\206\345\210\206" "b/2019.02.15-leetcode139/\345\215\225\350\257\215\346\213\206\345\210\206"
new file mode 100644
index 000000000..56946710c
--- /dev/null
+++ "b/2019.02.15-leetcode139/\345\215\225\350\257\215\346\213\206\345\210\206"
@@ -0,0 +1,21 @@
+给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
+
+说明:
+
+拆分时可以重复使用字典中的单词。
+你可以假设字典中没有重复的单词。
+示例 1:
+
+输入: s = "leetcode", wordDict = ["leet", "code"]
+输出: true
+解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
+示例 2:
+
+输入: s = "applepenapple", wordDict = ["apple", "pen"]
+输出: true
+解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
+     注意你可以重复使用字典中的单词。
+示例 3:
+
+输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
+输出: false
diff --git a/2019.02.16-leetcode474/TheRocket.md b/2019.02.16-leetcode474/TheRocket.md
new file mode 100644
index 000000000..dd05be56b
--- /dev/null
+++ b/2019.02.16-leetcode474/TheRocket.md
@@ -0,0 +1,31 @@
+```java
+class Solution {
+    public int findMaxForm(String[] strs, int m, int n) {
+        if (strs == null || strs.length == 0) {
+            return 0;
+        }
+        int[][] dp = new int[m + 1][n + 1];
+        for (String str : strs) {
+            int[] nums = count(str);
+            for (int i = m; i >= nums[0]; --i) {
+                for (int j = n; j >= nums[1]; --j) {
+                    dp[i][j] = Math.max(dp[i][j], dp[i - nums[0]][j - nums[1]] + 1);
+                }
+            }
+        }
+        return dp[m][n];
+    }
+
+    private int[] count(String str) {
+        int[] nums = new int[2];
+        for (char c : str.toCharArray()) {
+            if (c == '0') {
+                ++nums[0];
+            } else {
+                ++nums[1];
+            }
+        }
+        return nums;
+    }
+}
+```
diff --git "a/2019.02.16-leetcode474/\344\270\200\345\222\214\351\233\266" "b/2019.02.16-leetcode474/\344\270\200\345\222\214\351\233\266"
new file mode 100644
index 000000000..d96b5a85e
--- /dev/null
+++ "b/2019.02.16-leetcode474/\344\270\200\345\222\214\351\233\266"
@@ -0,0 +1,22 @@
+在计算机界中,我们总是追求用有限的资源获取最大的收益。
+
+现在,假设你分别支配着 m 个 0 和 n 个 1。另外,还有一个仅包含 0 和 1 字符串的数组。
+
+你的任务是使用给定的 m 个 0 和 n 个 1 ,找到能拼出存在于数组中的字符串的最大数量。每个 0 和 1 至多被使用一次。
+
+注意:
+
+给定 0 和 1 的数量都不会超过 100。
+给定字符串数组的长度不会超过 600。
+示例 1:
+
+输入: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
+输出: 4
+
+解释: 总共 4 个字符串可以通过 5 个 0 和 3 个 1 拼出,即 "10","0001","1","0" 。
+示例 2:
+
+输入: Array = {"10", "0", "1"}, m = 1, n = 1
+输出: 2
+
+解释: 你可以拼出 "10",但之后就没有剩余数字了。更好的选择是拼出 "0" 和 "1" 。
diff --git a/2019.02.17-leetcode322/Sagittarius.md b/2019.02.17-leetcode322/Sagittarius.md
new file mode 100644
index 000000000..33357b4c6
--- /dev/null
+++ b/2019.02.17-leetcode322/Sagittarius.md
@@ -0,0 +1,25 @@
+```
+class Solution {
+    public int coinChange(int[] coins, int amount) {
+        if(amount <= 0)
+            return 0;
+        
+        int[] minNum = new int[amount+1];
+        
+        for(int i=1;i<=amount;i++){
+            minNum[i]=Integer.MAX_VALUE;
+            
+            for(int j=0;j= coin) {
+                    dp[i] = Math.min(dp[i], dp[i - coin] + 1);
+                }
+            }
+        }
+        return dp[amount] != amount + 1 ? dp[amount] : -1;
+    }
+}
+```
diff --git "a/2019.02.17-leetcode322/\351\233\266\351\222\261\345\205\221\346\215\242" "b/2019.02.17-leetcode322/\351\233\266\351\222\261\345\205\221\346\215\242"
new file mode 100644
index 000000000..2af6c2ea2
--- /dev/null
+++ "b/2019.02.17-leetcode322/\351\233\266\351\222\261\345\205\221\346\215\242"
@@ -0,0 +1,13 @@
+给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
+
+示例 1:
+
+输入: coins = [1, 2, 5], amount = 11
+输出: 3 
+解释: 11 = 5 + 5 + 1
+示例 2:
+
+输入: coins = [2], amount = 3
+输出: -1
+说明:
+你可以认为每种硬币的数量是无限的。
diff --git a/2019.02.18-leetcode377/TheRocket.md b/2019.02.18-leetcode377/TheRocket.md
new file mode 100644
index 000000000..578c3c364
--- /dev/null
+++ b/2019.02.18-leetcode377/TheRocket.md
@@ -0,0 +1,16 @@
+```java
+class Solution {
+    public int combinationSum4(int[] nums, int target) {
+        int[] dp = new int[target + 1];
+        dp[0] = 1;
+        for (int i = 1; i <= target; ++i) {
+            for (int num : nums) {
+                if (i >= num) {
+                    dp[i] += dp[i - num];
+                }
+            }
+        }
+        return dp[target];
+    }
+}
+```
diff --git "a/2019.02.18-leetcode377/\347\273\204\345\220\210\346\200\273\345\222\214IV" "b/2019.02.18-leetcode377/\347\273\204\345\220\210\346\200\273\345\222\214IV"
new file mode 100644
index 000000000..f8d5caba2
--- /dev/null
+++ "b/2019.02.18-leetcode377/\347\273\204\345\220\210\346\200\273\345\222\214IV"
@@ -0,0 +1,23 @@
+给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。
+
+示例:
+
+nums = [1, 2, 3]
+target = 4
+
+所有可能的组合为:
+(1, 1, 1, 1)
+(1, 1, 2)
+(1, 2, 1)
+(1, 3)
+(2, 1, 1)
+(2, 2)
+(3, 1)
+
+请注意,顺序不同的序列被视作不同的组合。
+
+因此输出为 7。
+进阶:
+如果给定的数组中含有负数会怎么样?
+问题会产生什么变化?
+我们需要在题目中添加什么限制来允许负数的出现?
diff --git a/2019.02.19-leetcode309/TheRocket.md b/2019.02.19-leetcode309/TheRocket.md
new file mode 100644
index 000000000..ef3db5f26
--- /dev/null
+++ b/2019.02.19-leetcode309/TheRocket.md
@@ -0,0 +1,19 @@
+```java
+class Solution {
+    public int maxProfit(int[] prices) {
+        if (prices == null || prices.length <= 1) {
+            return 0;
+        }
+        int curSell = 0;
+        int preSell = 0;
+        int buy = -prices[0];
+        for (int i = 1; i < prices.length; ++i) {
+            int tmp = curSell;
+            curSell = Math.max(curSell, buy + prices[i]);
+            buy = Math.max(buy, preSell - prices[i]);
+            preSell = tmp;
+        }
+        return curSell;
+    }
+}
+```
diff --git "a/2019.02.19-leetcode309/\346\234\200\344\275\263\344\271\260\345\215\226\350\202\241\347\245\250\346\227\266\346\234\272\345\220\253\345\206\267\345\206\273\346\234\237" "b/2019.02.19-leetcode309/\346\234\200\344\275\263\344\271\260\345\215\226\350\202\241\347\245\250\346\227\266\346\234\272\345\220\253\345\206\267\345\206\273\346\234\237"
new file mode 100644
index 000000000..975221373
--- /dev/null
+++ "b/2019.02.19-leetcode309/\346\234\200\344\275\263\344\271\260\345\215\226\350\202\241\347\245\250\346\227\266\346\234\272\345\220\253\345\206\267\345\206\273\346\234\237"
@@ -0,0 +1,11 @@
+给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。​
+
+设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
+
+你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
+卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
+示例:
+
+输入: [1,2,3,0,2]
+输出: 3 
+解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
diff --git a/2019.02.20-leetcode714/TheRocket.md b/2019.02.20-leetcode714/TheRocket.md
new file mode 100644
index 000000000..39553ad58
--- /dev/null
+++ b/2019.02.20-leetcode714/TheRocket.md
@@ -0,0 +1,16 @@
+```java
+class Solution {
+    public int maxProfit(int[] prices, int fee) {
+        if (prices == null || prices.length <= 1) {
+            return 0;
+        }
+        int sell = 0;
+        int buy = -prices[0];
+        for (int i = 1; i < prices.length; ++i) {
+            sell = Math.max(sell, buy + prices[i] - fee);
+            buy = Math.max(buy, sell - prices[i]);
+        }
+        return sell;
+    }
+}
+```
diff --git "a/2019.02.20-leetcode714/\344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272\345\220\253\346\211\213\347\273\255\350\264\271" "b/2019.02.20-leetcode714/\344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272\345\220\253\346\211\213\347\273\255\350\264\271"
new file mode 100644
index 000000000..310c59cc6
--- /dev/null
+++ "b/2019.02.20-leetcode714/\344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272\345\220\253\346\211\213\347\273\255\350\264\271"
@@ -0,0 +1,21 @@
+给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。
+
+你可以无限次地完成交易,但是你每次交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
+
+返回获得利润的最大值。
+
+示例 1:
+
+输入: prices = [1, 3, 2, 8, 4, 9], fee = 2
+输出: 8
+解释: 能够达到的最大利润:  
+在此处买入 prices[0] = 1
+在此处卖出 prices[3] = 8
+在此处买入 prices[4] = 4
+在此处卖出 prices[5] = 9
+总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
+注意:
+
+0 < prices.length <= 50000.
+0 < prices[i] < 50000.
+0 <= fee < 50000.
diff --git "a/2019.02.21-leetcode123/\344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272III" "b/2019.02.21-leetcode123/\344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272III"
new file mode 100644
index 000000000..95cc9d0ad
--- /dev/null
+++ "b/2019.02.21-leetcode123/\344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272III"
@@ -0,0 +1,24 @@
+给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
+
+设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
+
+注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
+
+示例 1:
+
+输入: [3,3,5,0,0,3,1,4]
+输出: 6
+解释: 在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
+     随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。
+示例 2:
+
+输入: [1,2,3,4,5]
+输出: 4
+解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。   
+     注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。   
+     因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
+示例 3:
+
+输入: [7,6,4,3,1] 
+输出: 0 
+解释: 在这个情况下, 没有交易完成, 所以最大利润为 0。
diff --git "a/2019.02.22-leetcode188/\344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272IV" "b/2019.02.22-leetcode188/\344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272IV"
new file mode 100644
index 000000000..b0f7d85bb
--- /dev/null
+++ "b/2019.02.22-leetcode188/\344\271\260\345\215\226\350\202\241\347\245\250\347\232\204\346\234\200\344\275\263\346\227\266\346\234\272IV"
@@ -0,0 +1,17 @@
+给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
+
+设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。
+
+注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
+
+示例 1:
+
+输入: [2,4,1], k = 2
+输出: 2
+解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。
+示例 2:
+
+输入: [3,2,6,5,0,3], k = 2
+输出: 7
+解释: 在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
+     随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。
diff --git "a/2019.02.23-leetcode583/\344\270\244\344\270\252\345\255\227\347\254\246\344\270\262\347\232\204\345\210\240\351\231\244\346\223\215\344\275\234" "b/2019.02.23-leetcode583/\344\270\244\344\270\252\345\255\227\347\254\246\344\270\262\347\232\204\345\210\240\351\231\244\346\223\215\344\275\234"
new file mode 100644
index 000000000..2d95ce635
--- /dev/null
+++ "b/2019.02.23-leetcode583/\344\270\244\344\270\252\345\255\227\347\254\246\344\270\262\347\232\204\345\210\240\351\231\244\346\223\215\344\275\234"
@@ -0,0 +1,11 @@
+给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。
+
+示例 1:
+
+输入: "sea", "eat"
+输出: 2
+解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"
+说明:
+
+给定单词的长度不超过500。
+给定单词中的字符只含有小写字母。
diff --git "a/2019.02.24-leetcode72/\347\274\226\350\276\221\350\267\235\347\246\273" "b/2019.02.24-leetcode72/\347\274\226\350\276\221\350\267\235\347\246\273"
new file mode 100644
index 000000000..d64cde7ef
--- /dev/null
+++ "b/2019.02.24-leetcode72/\347\274\226\350\276\221\350\267\235\347\246\273"
@@ -0,0 +1,25 @@
+给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。
+
+你可以对一个单词进行如下三种操作:
+
+插入一个字符
+删除一个字符
+替换一个字符
+示例 1:
+
+输入: word1 = "horse", word2 = "ros"
+输出: 3
+解释: 
+horse -> rorse (将 'h' 替换为 'r')
+rorse -> rose (删除 'r')
+rose -> ros (删除 'e')
+示例 2:
+
+输入: word1 = "intention", word2 = "execution"
+输出: 5
+解释: 
+intention -> inention (删除 't')
+inention -> enention (将 'i' 替换为 'e')
+enention -> exention (将 'n' 替换为 'x')
+exention -> exection (将 'n' 替换为 'c')
+exection -> execution (插入 'u')
diff --git a/Sagittarius.md b/Sagittarius.md
new file mode 100644
index 000000000..9f630761c
--- /dev/null
+++ b/Sagittarius.md
@@ -0,0 +1,21 @@
+、、、
+class Solution {
+public:
+    bool isPalindrome(string s) {
+        if (s.empty()) return true;
+        
+        int l = 0, r = s.size() - 1;
+        while (l < r) {
+            if (!isalnum(s[l])) {
+              l++; continue;  
+            } 
+            if (!isalnum(s[r])) {
+              r--; continue;  
+            } 
+            if ((s[l] & 0xDF) != (s[r] & 0xDF)) return false;   //通过位与运算 使小写字母转变为大写     而位或运算(|0x20)可将大写变为小写
+            l++; r--;
+        }
+        return true;
+    }
+};
+、、、
diff --git a/Selfcenter.md b/Selfcenter.md
new file mode 100644
index 000000000..532af709d
--- /dev/null
+++ b/Selfcenter.md
@@ -0,0 +1,21 @@
+class Solution {
+    public boolean isPalindrome(String s) {
+	
+          String t = s.replaceAll("[^A-Za-z0-9]", "");
+          t = t.toLowerCase();
+         int start =0;
+         int end=t.length()-1;
+        while(start<=end){
+            if(t.charAt(start)!=t.charAt(end)) {
+                return false;
+            }
+            start++;
+            end--;
+            
+        }
+    
+        return true;
+        
+    }
+}
+       
diff --git a/fish.md b/fish.md
new file mode 100644
index 000000000..c33fe1152
--- /dev/null
+++ b/fish.md
@@ -0,0 +1,60 @@
+```
+public class Solution {
+  public static TreeNode binaryTree(TreeNode node, List preOrder, List inOrder) {
+    if (!preOrder.isEmpty()) {
+      Integer val = preOrder.get(0);
+      int preIndex = preOrder.indexOf(val);
+      int inIndex = inOrder.indexOf(val);
+      List plOrder = preOrder.subList(preIndex + 1, inIndex + 1);
+      List prOrder = preOrder.subList(inIndex + 1, preOrder.size());
+
+      List ilOrder = inOrder.subList(0, inIndex);
+      List irOrder = inOrder.subList(inIndex + 1, inOrder.size());
+      if (node == null) {
+        node = new TreeNode(val, null, null);
+      }
+      TreeNode lnode = null,rnode = null;
+      if (!plOrder.isEmpty()){
+        lnode = new TreeNode(plOrder.get(0), null, null);
+      }
+      if (!prOrder.isEmpty()) {
+        rnode = new TreeNode(prOrder.get(0), null, null);
+      }
+      node.setLeft(lnode);
+      node.setRight(rnode);
+      binaryTree(lnode, plOrder, ilOrder);
+      binaryTree(rnode, prOrder, irOrder);
+    }
+    return node;
+  }
+
+  public static void main(String[] args) {
+    List preOrder = new ArrayList<>();
+    preOrder.add(1);
+    preOrder.add(4);
+    preOrder.add(6);
+    preOrder.add(8);
+    preOrder.add(9);
+    preOrder.add(10);
+    preOrder.add(11);
+    List inOrder = new ArrayList<>();
+    inOrder.add(6);
+    inOrder.add(4);
+    inOrder.add(1);
+    inOrder.add(9);
+    inOrder.add(8);
+    inOrder.add(10);
+    inOrder.add(11);
+    System.out.println(binaryTree(null, preOrder, inOrder));
+  }
+}
+
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+@ToString
+class TreeNode {
+  private int val;
+  private TreeNode left;
+  private TreeNode right;
+}
\ No newline at end of file
diff --git a/leetcode203/Ostrichcrab.md b/leetcode203/Ostrichcrab.md
new file mode 100644
index 000000000..5c4c593a0
--- /dev/null
+++ b/leetcode203/Ostrichcrab.md
@@ -0,0 +1,28 @@
+```
+/**
+ * Definition for singly-linked list.
+ * struct ListNode {
+ *     int val;
+ *     ListNode *next;
+ *     ListNode(int x) : val(x), next(NULL) {}
+ * };
+ */
+class Solution {
+public:
+    ListNode* removeElements(ListNode* head, int val) {
+        if(head==NULL) return NULL;
+        while(head != NULL && head->val == val){
+            head = head->next;
+        }
+        if(head==NULL) return NULL;
+        ListNode* node = head;
+        while(node->next != NULL){
+            if(node->next->val==val)
+                node->next = node->next->next;
+            else
+                node = node->next;
+        }
+        return head;
+    }
+};
+```
diff --git "a/leetcode203/\345\256\266.md" "b/leetcode203/\345\256\266.md"
new file mode 100644
index 000000000..06fa7cffb
--- /dev/null
+++ "b/leetcode203/\345\256\266.md"
@@ -0,0 +1,16 @@
+```
+func removeElements(head *ListNode, val int) *ListNode {
+    prev := &ListNode{0,head}
+    c := prev
+    for head != nil{
+        if head.Val == val {
+            prev.Next = head.Next
+        }else{
+            prev = head
+        }
+        head = head.Next
+    }
+    return c.Next
+}
+    
+```
diff --git a/zjukk.md b/zjukk.md
new file mode 100644
index 000000000..b01b4fd2f
--- /dev/null
+++ b/zjukk.md
@@ -0,0 +1,28 @@
+```
+class Solution {
+public:
+    string reverseWords(string s) {
+        
+        istringstream is(s);
+        string res;
+        string tmp;
+        is >> tmp;//第一个字符串单独处理
+        res += reverse(tmp);
+        // cout << reverse(tmp);
+        while (is >> tmp) {
+            // cout << " " << reverse(tmp);
+            res += " ";
+            res += reverse(tmp);
+        }
+        return res;
+    }
+    string reverse(string& s) {
+        string res = s;
+        int n = s.size() - 1;
+        for (int i = 0; i < s.size(); ++i) {
+            res[i] = s[n-i];
+        }
+        return res;
+    }
+};
+```
diff --git "a/\345\246\256\345\217\257.md" "b/\345\246\256\345\217\257.md"
new file mode 100644
index 000000000..8d300f870
--- /dev/null
+++ "b/\345\246\256\345\217\257.md"
@@ -0,0 +1,58 @@
+```java
+package sy181214;
+
+import java.util.PriorityQueue;
+
+/**
+ * @author suyuan
+ * 
+ 在未排序的数组中找到第 k 个最大的元素。
+ 请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
+
+示例 1:
+
+输入: [3,2,1,5,6,4] 和 k = 2
+输出: 5
+示例 2:
+
+输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
+输出: 4
+说明:
+
+你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
+ */
+public class leetcode_215数组中的第K个最大元素
+{
+
+	public static void main(String[] args)
+	{
+		int [] input=new int[]{4,5,1,6,2,7,3,2,5,6};
+		System.out.println(findKthLargest(input, 4));
+
+	}
+	
+	 public static int findKthLargest(int[] nums, int k) 
+	 {
+	        int len=nums.length;
+	        if(k>len || k==0)
+	        	return 0;
+	        //小顶堆
+	        PriorityQueue que=new PriorityQueue(k);
+	        for(int i=0;i() {
+            @Override
+            public int compare(int[] n1, int[] n2) {//һ򣬵ڶ
+                if(n1[0] > n2[0]) {
+                    return -1;
+                }
+                if(n1[0] < n2[0]) {
+                    return 1;
+                } else {
+                    if(n1[1] < n2[1]) {
+                        return -1;
+                    } else {
+                        return 1;
+                    }
+                }
+            }
+        });
+        for(int i = 1; i < people.length; i++) {
+            int[] current = people[i];
+            int j;
+            int index = people[i][1];
+            for(j = i; j > index; j--) {
+                people[j] = people[j - 1];
+            }
+            people[j] = current;
+        }
+        
+        return people;
+    }
+}
\ No newline at end of file
diff --git "a/\351\235\222\350\241\253\345\277\206\347\254\231.md" "b/\351\235\222\350\241\253\345\277\206\347\254\231.md"
new file mode 100644
index 000000000..5c54b621e
--- /dev/null
+++ "b/\351\235\222\350\241\253\345\277\206\347\254\231.md"
@@ -0,0 +1,13 @@
+class Solution {
+    public int lengthOfLastWord(String s) {
+        if(s==null||s.length()==0) {
+			return 0;
+		}
+		char[] ch=s.toCharArray();
+		int i;
+		for(i=ch.length-1;i>=0&&ch[i]==' ';i--);
+		int j=i;
+		for(;j>=0&&ch[j]!=' ';j--);
+		return i-j;
+    }
+}