需常记心头
在二维火工作收集的经典语句!
题目链接:
Find Minimum in Rotated Sorted Array
Find Minimum in Rotated Sorted Array II
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
I和II的区别在于是否有重复元素
题目链接: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 | For example, given array S = [-1, 0, 1, 2, -1, -4], |
题目链接: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 | public static int[] megerArray(int[] A, int m, int[] B, int n){ |
题目链接: 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 | public static List<Integer> getRow(int row){ |