153, 题目:
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.
You may assume no duplicate exists in the array.
本题和之前的一道题目很相似,都是将排序数组在某处进行翻转,不同的是本题寻找最小值。思路也很简单,两种方法:直接遍历和binary search。代码入下:
public int findMin(int[] nums) {
for(int i=0; i<nums.length-1; i++){
if(nums[i] > nums[i+1])
return nums[i+1];
}
return nums[0];
}
public int findMin1(int[] nums){
int left=0, right=nums.length-1, mid;
while(left < right){
mid = (left + right)/2;
if(nums[mid] > nums[right]) {
if(mid < nums.length-1 && nums[mid] > nums[mid+1])
return nums[mid+1];
left = mid+1;
}
else{
if(mid >0 && nums[mid] < nums[mid-1])
return nums[mid];
right = mid-1;
}
}
return nums[0];
}
public int findMin2(int[] nums) {
int start = 0, end = nums.length - 1, mid;
while (start < end) {
mid = (start + end) / 2;
if (nums[mid] > nums[end])
start = mid + 1;
else
end = mid;
}
return nums[start];
}
238,题目:
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
本题是求元素乘积(除了该位置元素外的其他所有元素)。很简单,一开始想到的方法比如,求所有元素之积然后除,背题目限制。然后还可以暴力遍历每个元素对其他元素求积,但是会超过时间限制。最后想到可以使用两次遍历的方法,第一次遍历得到该元素之前的所有元素之积,然后第二次进行反向遍历,用于求除去该元素之外所有元素之积。例如:
[1,2,3,4,5,6,7]
第一次:[1,1,2,6,24,120,720]
第二次:[....6*1*7*6*5, 24*1*7*6, 120*1*7, 720*1]
代码入下:
//暴力法
public int[] productExpectSelf1(int[] nums){
int[] res = new int[nums.length];
for(int i=0; i<nums.length; i++){
int tmp = 1;
for(int j=0; j<nums.length; j++)
if(j != i)
tmp *= nums[j];
res[i] = tmp;
}
return res;
}
//两次遍历法
public int[] productExceptSelf2(int[] nums) {
int n = nums.length;
int[] res = new int[n];
res[0] = 1;
for (int i = 1; i < n; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = n - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}

270

被折叠的 条评论
为什么被折叠?



