41. First Missing Positive
网上这道题的做法很多,有用桶排序的,有用hash的。
我这里用桶排序。思路是将数组中的元素nums[i]交换nums[nums[i] - 1]里面,有些情况是不交换的。。。
public class Solution {
public int firstMissingPositive(int[] nums) {for (int i = 0; i < nums.length; i++) {
while(nums[i] != i+1) {
if (nums[i] <= 0 || nums.length <= nums[i] || nums[i] == nums[nums[i] - 1]) {
break;
}
int temp = nums[i];
nums[i] = nums[nums[i] - 1];
nums[temp - 1] = temp;
}
}
for (int i = 0; i < nums.length; i++) {
if(nums[i] != i+1)
return i+1;
}
return nums.length + 1;
}
}
42. Trapping Rain Water
这道题用两个索引从两边开始夹逼比较简单。两个索引对应数组值先比较谁更小,更小的为高度。接下来往中间移动,碰到小于上一位的情况,water量加上(上一位高度 - 当前高度)。。。。
public class Solution {
public int trap(int[] height) {
if (height == null || height.length < 3) {
return 0;
}
int first = 0;
int last = height.length - 1;
int water = 0;
while (first < last) {
int minH = Math.min(height[first], height[last]);
if (height[first] == minH) {
while (++first < last && height[first] < minH) {
water += minH - height[first];
}
}
else {
while (first < --last && height[last] < minH) {
water += minH - height[last];
}
}
}
return water;
}
}
48. Rotate Image
这道题一次要换四个,容易弄乱。。。注意的是1 循环开始的位置 2 循环结束位置 3 交换方法,A<B, B<C, C<D, D<A。
答案见这里:
http://blog.csdn.net/u012848330/article/details/52702326
53. Maximum Subarray
public class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0){
return 0;
}
int max = Integer.MIN_VALUE, sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
max = Math.max(max, sum);
sum = Math.max(sum, 0);
}
return max;
}
}