-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicatesFormArray.java
More file actions
84 lines (80 loc) · 3.04 KB
/
RemoveDuplicatesFormArray.java
File metadata and controls
84 lines (80 loc) · 3.04 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package basic.doublePointer;
/**
* leetcode26 https://leetcode.com/problems/remove-duplicates-from-sorted-array/
* leetcode80 https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
*/
public class RemoveDuplicatesFormArray {
public static void main(String[] args) {
RemoveDuplicatesFormArray removeDuplicatesFormArray = new RemoveDuplicatesFormArray();
removeDuplicatesFormArray.removeDuplicates(new int[]{1, 1, 2});
}
/**
* 26. Remove Duplicates from Sorted Array
* 给定一个有序数组,原地删除重复元素,保证每个元素只出现一次并返回新的数组长度
* Example 1:
* <p>
* Input: nums = [1,1,2]
* Output: 2, nums = [1,2]
* Explanation: 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 returned length.
* Example 2:
* <p>
* Input: nums = [0,0,1,1,1,2,2,3,3,4]
* Output: 5, nums = [0,1,2,3,4]
* Explanation: Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.
*
* @param nums
* @return
*/
public int removeDuplicates(int[] nums) {
int i=0;
for (int n: nums) {
if(i<1 || n > nums[i-1]) {
nums[i++]=n;
}
}
return i;
/* 解法2
if (nums == null) return 0;
if (nums.length <= 1) return nums.length;
int d = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1]) {
nums[d++] = nums[i];
}
}
return d;*/
}
/**
* 80. Remove Duplicates from Sorted Array II
* 给定一个有序数组,去除多余元素,使得其中的每个元素最多出现两次
* Example 1:
* <p>
* Input: nums = [1,1,1,2,2,3],
* Output:5
* <p>
* Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
* <p>
* It doesn't matter what you leave beyond the returned length.
* Example 2:
* <p>
* Input: nums = [0,0,1,1,1,1,2,3,3],
* OutPut: 7
* <p>
* Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
* <p>
* It doesn't matter what values are set beyond the returned length.
*
* @param nums
* @return
*/
public int removeDuplicates2(int[] nums) {
int i = 0;
for (int n : nums) {
//n > nums[i - 2],如果连续有三个以上的重复元素,则第三个及以后的重复元素不会进入到此循环中,因此可以保证i左侧的元素都是满足条件的。
if (i < 2 || n > nums[i - 2]) {
nums[i++] = n;
}
}
return i;
}
}