Skip to content

Commit 4b68079

Browse files
committed
旧代码初步整理完成
1 parent ed121be commit 4b68079

File tree

29 files changed

+1232
-25
lines changed

29 files changed

+1232
-25
lines changed

Leetcode/array/3Sum/readme.md

+168
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
# 15. 3Sum
2+
3+
tags: Array, Two Pointers
4+
5+
---
6+
7+
## 题目原文
8+
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
9+
10+
Note: The solution set must not contain duplicate triplets.
11+
12+
For example, given array S = [-1, 0, 1, 2, -1, -4],
13+
14+
A solution set is:
15+
16+
[
17+
[-1, 0, 1],
18+
[-1, -1, 2]
19+
]
20+
21+
## 题目大意
22+
给定一个整型数组num, 找出这个数组中满足这个条件的所有数字: num[i]+num[j]+num[k] = 0. 并且所有
23+
的答案是要和其他不同的, 也就是说两个相同的答案是不被接受的。
24+
题目的两点要求:
25+
1. 每个答案组里面的三个数字是要从大到小排列起来的。
26+
2. 每个答案不可以和其他的答案相同。
27+
28+
29+
30+
## 解题思路
31+
### 网上分析1
32+
题目分析:
33+
34+
1. 每一个答案数组triplet中的元素是要求升序排列的。
35+
2. 不能包含重复的答案数组。
36+
37+
解题思路:
38+
1. 根据第一点要求: 因为要求每个答案数组中的元素是升序排列的, 所以在开头我们要对数组进行排
39+
序。
40+
2. 根据第二点要求: 因为不能包含重复的答案数组, 所以我们要在代码里面做一切去掉重复的操作, 对
41+
于数组, 这样的操作是相同的。 最开始我做leetcode的时候是把所有满足条件的答案数组存起来, 之后
42+
再用map进行处理, 感觉那样太麻烦了, 所以这次给出的答案是不需要额外空间的。
43+
44+
时间复杂度分析:
45+
对于这道题, 因为是要找三个元素, 所以怎样都要O(n2)的时间复杂度, 目前我没有想出来O(n)时间复杂度
46+
的解法。
47+
48+
归根结底, 其实这是two pointers的想法, 定位其中两个指针, 根据和的大小来移动另外一个。 解题中要
49+
注意的就是一些细节问题。 好了, 上代码吧。
50+
51+
### 网上分析2
52+
the key idea is the same as the TwoSum problem. When we fix the 1st number,the 2nd and 3rd number can be found following the same reasoning as TwoSum.
53+
54+
The only difference is that, the TwoSum problem of LEETCODE has a unique solution.However, in ThreeSum, we have multiple duplicate solutions that can be found. Most ofthe OLE errors happened here because you could've ended up with a solution with so manyduplicates.
55+
56+
The naive solution for the duplicates will be using the STL methods like below :
57+
58+
std::sort(res.begin(), res.end());
59+
60+
res.erase(unique(res.begin(), res.end()), res.end());
61+
62+
But according to my submissions, this way will cause you double your time consumingalmostly.
63+
A better approach is that, to jump over the number which has been scanned, no matter itis part of some solution or not.
64+
65+
If the three numbers formed a solution, we can safely ignore all the duplicates of them.
66+
We can do this to all the three numbers such that we can remove the duplicates.
67+
Here's my AC C++ Code:
68+
69+
### 我的分析:
70+
71+
主要是先将原数组排序,并充分利用排序好的数组的特性。去除重复答案的方法是,先按index从小到大确定第一个元素,在按(bengin=index)++和(end)--的顺序确定第二个元素和第三个元素,当begin=begin+1是跳过,end同理,第一个元素的所有可能循环完成后,index++之前也要判断index是否等于index+1。总而言之就是利用排序号数组特性保证每个元素都各不相同。先确定答案中最小的数,防止答案中出现重复的组合
72+
73+
74+
75+
## 代码
76+
### [c++代码](./src/cpp/3Sum.cpp)
77+
```c++
78+
class Solution {
79+
public:
80+
vector<vector<int>> threeSum(vector<int>& nums) {
81+
std::sort(nums.begin(),nums.end());
82+
vector<vector<int >> res;
83+
for(int i=0;i<nums.size();i++){
84+
int target=-nums[i];
85+
int front=i+1;
86+
int back=nums.size()-1;
87+
while(front<back){
88+
int sum=nums[front]+nums[back];
89+
if(sum>target)
90+
back--;
91+
else if(sum<target)
92+
front++;
93+
else{
94+
vector<int> tri(3,0);
95+
tri[0]=nums[i];
96+
tri[1]=nums[front];
97+
tri[2]=nums[back];
98+
res.push_back(tri);
99+
100+
while(front<back&&nums[front]==tri[1]) front++;
101+
while(front<back&&nums[back]==tri[2]) back--;
102+
103+
104+
}
105+
while(i+1<nums.size()&&nums[i+1]==nums[i]) i++;
106+
}
107+
}
108+
return res;
109+
}
110+
};
111+
```
112+
113+
### [python代码](./src/python/3Sum.py)
114+
```python
115+
cimport collections
116+
117+
118+
class Solution(object):
119+
        def threeSum(self, nums):
120+
                """
121+
:type nums: List[int]
122+
:rtype: List[List[int]]
123+
"""
124+
                nums, result, i = sorted(nums), [], 0
125+
                while i < len(nums) - 2:
126+
                        if i == 0 or nums[i] != nums[i - 1]:
127+
                                j, k = i + 1, len(nums) - 1
128+
                                while j < k:
129+
                                        if nums[i] + nums[j] + nums[k] < 0:
130+
                                                j += 1
131+
                                        elif nums[i] + nums[j] + nums[k] > 0:
132+
                                                k -= 1
133+
                                        else:
134+
                                                result.append([nums[i], nums[j], nums[k]])
135+
                                                j, k = j + 1, k - 1
136+
                                                while j < k and nums[j] == nums[j - 1]:
137+
                                                        j += 1
138+
                                                while j < k and nums[k] == nums[k + 1]:
139+
                                                        k -= 1
140+
                        i += 1
141+
                return result
142+
143+
        def threeSum2(self, nums):
144+
                """
145+
:type nums: List[int]
146+
:rtype: List[List[int]]
147+
"""
148+
                d = collections.Counter(nums)
149+
                nums_2 = [x[0] for x in d.items() if x[1] > 1]
150+
                nums_new = sorted([x[0] for x in d.items()])
151+
                rtn = [[0, 0, 0]] if d[0] >= 3 else []
152+
                for i, j in enumerate(nums_new):
153+
                        if j <= 0:
154+
                                numss2 = nums_new[i + 1:]
155+
                                for x, y in enumerate(numss2):
156+
                                        if 0 - j - y in [j, y] and 0 - j - y in nums_2:
157+
                                                if sorted([j, y, 0 - j - y]) not in rtn:
158+
                                                        rtn.append(sorted([j, y, 0 - j - y]))
159+
                                        if 0 - j - y not in [j, y] and 0 - j - y in nums_new:
160+
                                                if sorted([j, y, 0 - j - y]) not in rtn:
161+
                                                        rtn.append(sorted([j, y, 0 - j - y]))
162+
                return rtn
163+
164+
if __name__ == '__main__':
165+
        result = Solution().threeSum([-1, 0, 1, 2, -1, -4])
166+
        print result
167+
168+
```

Leetcode/array/3Sum/src/cpp/3Sum.cpp

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> threeSum(vector<int>& nums) {
4+
std::sort(nums.begin(),nums.end());
5+
vector<vector<int >> res;
6+
for(int i=0;i<nums.size();i++){
7+
int target=-nums[i];
8+
int front=i+1;
9+
int back=nums.size()-1;
10+
while(front<back){
11+
int sum=nums[front]+nums[back];
12+
if(sum>target)
13+
back--;
14+
else if(sum<target)
15+
front++;
16+
else{
17+
vector<int> tri(3,0);
18+
tri[0]=nums[i];
19+
tri[1]=nums[front];
20+
tri[2]=nums[back];
21+
res.push_back(tri);
22+
23+
while(front<back&&nums[front]==tri[1]) front++;
24+
while(front<back&&nums[back]==tri[2]) back--;
25+
26+
27+
}
28+
while(i+1<nums.size()&&nums[i+1]==nums[i]) i++;
29+
}
30+
}
31+
return res;
32+
}
33+
};
+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import collections
2+
3+
4+
class Solution(object):
5+
        def threeSum(self, nums):
6+
                """
7+
:type nums: List[int]
8+
:rtype: List[List[int]]
9+
"""
10+
                nums, result, i = sorted(nums), [], 0
11+
                while i < len(nums) - 2:
12+
                        if i == 0 or nums[i] != nums[i - 1]:
13+
                                j, k = i + 1, len(nums) - 1
14+
                                while j < k:
15+
                                        if nums[i] + nums[j] + nums[k] < 0:
16+
                                                j += 1
17+
                                        elif nums[i] + nums[j] + nums[k] > 0:
18+
                                                k -= 1
19+
                                        else:
20+
                                                result.append([nums[i], nums[j], nums[k]])
21+
                                                j, k = j + 1, k - 1
22+
                                                while j < k and nums[j] == nums[j - 1]:
23+
                                                        j += 1
24+
                                                while j < k and nums[k] == nums[k + 1]:
25+
                                                        k -= 1
26+
                        i += 1
27+
                return result
28+
29+
        def threeSum2(self, nums):
30+
                """
31+
:type nums: List[int]
32+
:rtype: List[List[int]]
33+
"""
34+
                d = collections.Counter(nums)
35+
                nums_2 = [x[0] for x in d.items() if x[1] > 1]
36+
                nums_new = sorted([x[0] for x in d.items()])
37+
                rtn = [[0, 0, 0]] if d[0] >= 3 else []
38+
                for i, j in enumerate(nums_new):
39+
                        if j <= 0:
40+
                                numss2 = nums_new[i + 1:]
41+
                                for x, y in enumerate(numss2):
42+
                                        if 0 - j - y in [j, y] and 0 - j - y in nums_2:
43+
                                                if sorted([j, y, 0 - j - y]) not in rtn:
44+
                                                        rtn.append(sorted([j, y, 0 - j - y]))
45+
                                        if 0 - j - y not in [j, y] and 0 - j - y in nums_new:
46+
                                                if sorted([j, y, 0 - j - y]) not in rtn:
47+
                                                        rtn.append(sorted([j, y, 0 - j - y]))
48+
                return rtn
49+
50+
if __name__ == '__main__':
51+
        result = Solution().threeSum([-1, 0, 1, 2, -1, -4])
52+
        print result
+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
88. Merge Sorted Array
2+
3+
tags: Array
4+
5+
---
6+
7+
## 题目原文
8+
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
9+
10+
Note:
11+
12+
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
13+
## 题目大意
14+
nums1和nums2是两个排序好的数组,把两个数组合并放入nums1并排好序。
15+
16+
17+
## 解题思路
18+
A和B都已经是排好序的数组, 我们只需要从后往前比较就可以了。
19+
20+
因为A有足够的空间容纳A + B, 我们使用游标i指向m + n - 1, 也就是最大数值存放的地方, 从后往前遍历A, B, 谁大就放到i这里, 同时递减i。
21+
22+
23+
24+
## 代码
25+
### [c++代码](./src/cpp/MergeSortedArray.cpp)
26+
```c++
27+
class Solution {
28+
public:
29+
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
30+
int idx1=m-1;
31+
int idx2=n-1;
32+
//int idx=m+n-1;
33+
for (int idx=m+n-1;idx>=0;idx--){
34+
if(idx1>=0&&idx2>=0){
35+
if (nums1[idx1]>=nums2[idx2])
36+
nums1[idx]=nums1[idx1--];
37+
else
38+
nums1[idx]=nums2[idx2--];
39+
}else{
40+
if (idx1>=0)
41+
nums1[idx]=nums1[idx1--];
42+
43+
else
44+
nums1[idx]=nums2[idx2--];
45+
}
46+
}
47+
}
48+
};
49+
```
50+
51+
### [python代码](./src/python/MergeSortedArray.py)
52+
```python
53+
class Solution:
54+
        # @param A a list of integers
55+
        # @param m an integer, length of A
56+
        # @param B a list of integers
57+
        # @param n an integer, length of B
58+
        # @return nothing
59+
        def merge(self, A, m, B, n):
60+
                last, i, j = m + n - 1, m - 1, n - 1
61+
                
62+
                while i >= 0 and j >= 0:
63+
                        if A[i] > B[j]:
64+
                                A[last] = A[i]
65+
                                last, i = last - 1, i - 1
66+
                        else:
67+
                                A[last] = B[j]
68+
                                last, j = last - 1, j - 1
69+
                
70+
                while j >= 0:
71+
                                A[last] = B[j]
72+
                                last, j = last - 1, j - 1
73+
74+
if __name__ == "__main__":
75+
        A = [1, 3, 5, 0, 0, 0, 0]
76+
        B = [2, 4, 6, 7]
77+
        Solution().merge(A, 3, B, 4)
78+
        print A
79+
80+
81+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public:
3+
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
4+
int idx1=m-1;
5+
int idx2=n-1;
6+
//int idx=m+n-1;
7+
for (int idx=m+n-1;idx>=0;idx--){
8+
if(idx1>=0&&idx2>=0){
9+
if (nums1[idx1]>=nums2[idx2])
10+
nums1[idx]=nums1[idx1--];
11+
else
12+
nums1[idx]=nums2[idx2--];
13+
}else{
14+
if (idx1>=0)
15+
nums1[idx]=nums1[idx1--];
16+
17+
else
18+
nums1[idx]=nums2[idx2--];
19+
}
20+
}
21+
}
22+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
        # @param A a list of integers
3+
        # @param m an integer, length of A
4+
        # @param B a list of integers
5+
        # @param n an integer, length of B
6+
        # @return nothing
7+
        def merge(self, A, m, B, n):
8+
                last, i, j = m + n - 1, m - 1, n - 1
9+
                
10+
                while i >= 0 and j >= 0:
11+
                        if A[i] > B[j]:
12+
                                A[last] = A[i]
13+
                                last, i = last - 1, i - 1
14+
                        else:
15+
                                A[last] = B[j]
16+
                                last, j = last - 1, j - 1
17+
                
18+
                while j >= 0:
19+
                                A[last] = B[j]
20+
                                last, j = last - 1, j - 1
21+
22+
if __name__ == "__main__":
23+
        A = [1, 3, 5, 0, 0, 0, 0]
24+
        B = [2, 4, 6, 7]
25+
        Solution().merge(A, 3, B, 4)
26+
        print A
27+

0 commit comments

Comments
 (0)