复习第三遍
移除元素
方法一: 暴力 空间复杂度O(n^2),时间复杂度O(1)
class Solution {
public int removeDuplicates(int[] nums) {
int length = nums.length;;
for (int i = 1; i < length; i++) {
if (nums[i-1] == nums[i]) {
this.removeElement(nums, i);
i--;
length--;
}
}
return length;
}
public void removeElement(int[] nums, int index) {
for (int i = index + 1; i < nums.length; i++) {
nums[i-1] = nums[i];
}
}
}
写错的1 this.不是self. 2 返回值为void写成了int
方法二 时间复杂度: O(n), 空间复杂度O(1)
class Solution {
public int removeDuplicates(int[] nums) {
int j = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[j]) {
j++;
nums[j] = nums[i];
}
}
return j + 1;
}
}
class Solution {
public int removeDuplicates(int[] nums) {
int p = 0;
int q = 1;
int j = nums.length;
while (q < j) {
if (nums[q] != nums[p]) {
p++;
nums[p] = nums[q];
}
q++;
}
return p + 1;
}
}
写错,while循环中,将int j = nums.length - 1;显然错了
盛最多水的容器
方法一:暴力法 空间复杂度O(n^2),时间复杂度O(1)
class Solution {
public int maxArea(int[] height) {
int res = 0;
for (int i = 0; i < height.length - 1; i++) {
for (int j = i + 1; j < height.length; j++) {
res = Math.max(res, (height[i] < height[j]) ? height[i] * (j - i) : height[j] * (j - i));
}
}
return res;
}
}
方法二 双指针法 时间复杂度O(n),空间复杂度O(1)
class Solution {
public int maxArea(int[] height) {
int res = 0;
int left = 0;
int right = height.length - 1;
while (left < right) {
int minHeight = Math.min(height[left], height[right]);
res = Math.max(res, minHeight * (right - left));
if (height[left] == minHeight) {
left++;
}else {
right--;
}
}
return res;
}
}
发现的问题,当我想用一行表达的时候
class Solution {
public int maxArea(int[] height) {
int res = 0;
int left = 0;
int right = height.length - 1;
while (left < right) {
res = Math.max(res,height[left] < height[right] ? height[left++] * (right - left) : height[right--] * (right - left));
}
return res;
}
}
// 因为height[left++]在之后left++了,所以导致(right - left)的值错了