Fighting!

潜行者的沉默

题目链接:3Sum
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.
Note: The solution set must not contain duplicate triplets.

1
2
3
4
5
6
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
阅读全文 »

想做一个会阅读的人!
阅读的目的可以从三方面理解:
1.获取资讯,2.为了娱乐,3.增进阅读的理解力。
会读书的人都是主动的阅读,为了提高阅读的理解力。

阅读全文 »

题目链接:Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
由题意得:
1.A和B两个数组都是有序的数组,大小分别为m和n
2.合并两数组在A数组中,A数组容量足够大。
思路分析:如果暴力解法即(无脑解法),遍历A数组和B数组每个元素比较,若A[i] < B[j],则继续比较下一个B元素,否则将A数组i及之后的元素往后移动以为。这种解法想想就不可能。换一种思路两数组都反向递减遍历。两数组总长度index = m+n-1, 遍历若A[i] < B[j],则A[index] = A[j] j–,否则A[index] = B[i] i–,index–。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static int[] megerArray(int[] A, int m, int[] B, int n){
int aCount = m-1, bCount = n-1, index = m+n-1;
while (index >= 0){
if(aCount>=0 && bCount>=0){
if(A[aCount] > B[bCount]){
A[index] = A[aCount];
aCount--;
}else {
A[index] = A[bCount];
bCount--;
}
}else if(aCount >= 0){
A[index] = A[aCount];
aCount--;
}else if(bCount >=0){
A[index] = A[bCount];
bCount--;
}
index--;
}
return A;
}

题目链接: Pascal’s Triangle II
Given an index k, return the kth row of the Pascal’s triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

这道题跟Pascal’s Triangle很类似,只是这里只需要求出某一行的结果。Pascal’s Triangle中因为是求出全部结果,所以我们需要上一行的数据就很自然的可以去取。而这里我们只需要一行数据,就得考虑一下是不是能只用一行的空间来存储结果而不需要额外的来存储上一行呢?这里确实是可以实现的。对于每一行我们知道如果从前往后扫,第i个元素的值等于上一行的list[i]+list[i-1],可以看到数据是往前看的,如果我们只用一行空间,那么需要的数据就会被覆盖掉。所以这里采取的方法是从后往前扫,这样每次需要的数据就是list[i]+list[i-1],我们需要的数据不会被覆盖,因为需要的res[i]只在当前步用,下一步就不需要了。这个技巧在动态规划省空间时也经常使用,主要就是看我们需要的数据是原来的数据还是新的数据来决定我们遍历的方向。时间复杂度还是O(n^2),而空间这里是O(k)来存储结果,仍然不需要额外空间。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static List<Integer> getRow(int row){
List<Integer> list = new ArrayList<>();
if(row<0)
return list;
list.add(1);
for (int line = 1; line < row; line++){
for (int index = list.size() - 1; index > 0; index --){
list.set(index, list.get(index-1)+list.get(index));
}
list.add(1);
}
return list;
}
0%