-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathRemoveDuplicatesFromSortedArray.java
More file actions
77 lines (73 loc) · 3.16 KB
/
Copy pathRemoveDuplicatesFromSortedArray.java
File metadata and controls
77 lines (73 loc) · 3.16 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
/**
* <p>给你一个有序数组 <code>nums</code> ,请你<strong><a href="http://baike.baidu.com/item/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95" target="_blank"> 原地</a></strong> 删除重复出现的元素,使每个元素 <strong>只出现一次</strong> ,返回删除后数组的新长度。</p>
*
* <p>不要使用额外的数组空间,你必须在 <strong><a href="https://baike.baidu.com/item/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95" target="_blank">原地 </a>修改输入数组 </strong>并在使用 O(1) 额外空间的条件下完成。</p>
*
* <p> </p>
*
* <p><strong>说明:</strong></p>
*
* <p>为什么返回数值是整数,但输出的答案是数组呢?</p>
*
* <p>请注意,输入数组是以<strong>「引用」</strong>方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。</p>
*
* <p>你可以想象内部操作如下:</p>
*
* <pre>
* // <strong>nums</strong> 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
* int len = removeDuplicates(nums);
*
* // 在函数里修改输入数组对于调用者是可见的。
* // 根据你的函数返回的长度, 它会打印出数组中<strong> 该长度范围内</strong> 的所有元素。
* for (int i = 0; i < len; i++) {
* print(nums[i]);
* }
* </pre>
*
*
* <p><strong>示例 1:</strong></p>
*
* <pre>
* <strong>输入:</strong>nums = [1,1,2]
* <strong>输出:</strong>2, nums = [1,2]
* <strong>解释:</strong>函数应该返回新的长度 <strong><code>2</code></strong> ,并且原数组 <em>nums </em>的前两个元素被修改为 <strong><code>1</code></strong>, <strong><code>2 </code></strong><code>。</code>不需要考虑数组中超出新长度后面的元素。
* </pre>
*
* <p><strong>示例 2:</strong></p>
*
* <pre>
* <strong>输入:</strong>nums = [0,0,1,1,1,2,2,3,3,4]
* <strong>输出:</strong>5, nums = [0,1,2,3,4]
* <strong>解释:</strong>函数应该返回新的长度 <strong><code>5</code></strong> , 并且原数组 <em>nums </em>的前五个元素被修改为 <strong><code>0</code></strong>, <strong><code>1</code></strong>, <strong><code>2</code></strong>, <strong><code>3</code></strong>, <strong><code>4</code></strong> 。不需要考虑数组中超出新长度后面的元素。
* </pre>
*
* <p> </p>
*
* <p><strong>提示:</strong></p>
*
* <ul>
* <li><code>0 <= nums.length <= 3 * 10<sup>4</sup></code></li>
* <li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
* <li><code>nums</code> 已按升序排列</li>
* </ul>
*
* <p> </p>
* <div><div>Related Topics</div><div><li>数组</li><li>双指针</li></div></div><br><div><li>👍 2303</li><li>👎 0</li></div>
*/
package leetcode1;
public class RemoveDuplicatesFromSortedArray {
public static void main(String[] args) {
Solution solution = new RemoveDuplicatesFromSortedArray().new Solution();
}
class Solution {
public int removeDuplicates(int[] nums) {
int j = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1]) {
nums[j++] = nums[i];
}
}
return j;
}
}
}