12周刷题大作战

你到底什么时候能转行成功?

LeetCode - 26, 27, 80 (2 Easy, 1 Medium, 0 Hard)

26. Remove Duplicates from Sorted Array - Easy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class  {
public int removeDuplicates(int[] nums) {
if(nums.length == 0){
return 0;
}

int end = 0;
for (int i = 1; i < nums.length; i++){
if (nums[end] != nums[i]){
end ++;
nums[end] = nums[i];
}
}

return end+1;
}
}

27. Remove Element - Easy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

class {
public int removeElement(int[] nums, int val) {
if(nums.length == 0){
return 0;
}

int end = 0;
for (int i = 0; i < nums.length; i++){
if(nums[i] != val){
nums[end] = nums[i];
end++;
}
}
return end;
}
}

80. Remove Duplicates from Sorted Array II - Medium


我的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class  {
public int removeDuplicates(int[] nums) {
if(nums.length == 0){
return 0;
}

int end = 0;
int count = 1;
for (int i = 1; i < nums.length; i++){
if (count == 1){
if (nums[i] == nums[end]){
count++;
}
end++;
nums[end] = nums[i];
}else{
if(nums[i] != nums[end]){
end ++;
nums[end] = nums[i];
count = 1;
}
}
}
return end+1;
}
}

老师的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class  {
public int removeDuplicates(int[] nums) {
if (nums.length <= 2){
return nums.length;
}

int end = 1;
for (int i = 2; i < nums.length; i ++){
if(nums[end-1] != nums[i]){
end ++;
nums[end] = nums[i];
}
}
return end+1;
}
}

明天学StringBuilder