[leetcode]remove duplicates from sorted array i ii

Remove Duplicates from Sorted Array I

题目描述

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {

// if(nums == null || nums.length == 0) return 0;
// int newLength = 1;
// for(int i = 1; i < nums.length; i++){
// if(nums[i] != nums[i-1]) nums[newLength++] = nums[i];
// }

// return newLength;
// }

public int (int[] nums){
if(nums == null || nums.length == 0) return 0;
int i = 0;
for(int num: nums){
//第一个元素直接往里面放,后面nums[i]只要不跟前一个放进去的相等都能往里面放
if(i < 1 || num != nums[i-1])
nums[i++] = num;
}
return i;
}
}

Remove Duplicates from Sorted Array II

题目描述

Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public int (int[] nums) {
if(nums == null || nums.length == 0) return 0;
int i = 0;
//前两个元素直接加入,后面的元素nums[i]只要不跟前面倒数第二个放进去的nums[i-2]相等都能往里面放
for(int num: nums){
if(i < 2 || num != nums[i-2])
nums[i++] = num;
}

return i;
}
}