Skip to content

Commit e4dddc0

Browse files
authored
Create syuan.md
1 parent 46a402c commit e4dddc0

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

2018.11.25-leetcode80/syuan.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
##### 题目
2+
3+
```
4+
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。
5+
6+
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
7+
8+
示例 1:
9+
10+
给定 nums = [1,1,1,2,2,3],
11+
12+
函数应返回新长度 length = 5, 并且原数组的前五个元素被修改为 1, 1, 2, 2, 3 。
13+
14+
你不需要考虑数组中超出新长度后面的元素。
15+
16+
示例 2:
17+
18+
给定 nums = [0,0,1,1,1,1,2,3,3],
19+
20+
函数应返回新长度 length = 7, 并且原数组的前五个元素被修改为 0, 0, 1, 1, 2, 3, 3 。
21+
22+
你不需要考虑数组中超出新长度后面的元素。
23+
24+
说明:
25+
26+
为什么返回数值是整数,但输出的答案是数组呢?
27+
28+
请注意,输入数组是以“引用”方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。
29+
30+
你可以想象内部操作如下:
31+
32+
// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
33+
int len = removeDuplicates(nums);
34+
35+
// 在函数里修改输入数组对于调用者是可见的。
36+
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
37+
for (int i = 0; i < len; i++) {
38+
print(nums[i]);
39+
}
40+
```
41+
##### 代码
42+
43+
```
44+
class Solution {
45+
public int removeDuplicates(int[] nums) {
46+
int count=0;
47+
if (nums.length==1) {
48+
return 1;
49+
}
50+
if (nums.length==0) {
51+
return 0;
52+
}
53+
if (nums.length==2) {
54+
return 2;
55+
}
56+
int i=0;
57+
int j=i;
58+
int tempCount=0;
59+
while(i<nums.length)
60+
{
61+
if (j<nums.length && nums[j]==nums[i]) {
62+
j++;
63+
tempCount++;
64+
}else{
65+
if (tempCount>=2) {
66+
count+=2;
67+
nums[i+1]=nums[i];
68+
i=i+2;
69+
}else{
70+
count++;
71+
i++;
72+
}
73+
if (j>=nums.length) {
74+
break;
75+
}
76+
nums[i]=nums[j];
77+
tempCount=0;
78+
}
79+
}
80+
return count;
81+
}
82+
}
83+
```

0 commit comments

Comments
 (0)