Skip to content

Commit f2802c8

Browse files
author
刘勋
committed
删除排序数组中的重复项
1 parent 43565e6 commit f2802c8

4 files changed

Lines changed: 53 additions & 22 deletions

File tree

src/main/java/com/algorithm/study/demo/Demo1.java

Lines changed: 0 additions & 19 deletions
This file was deleted.

src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package com.algorithm.study.demo.algorithm.leetcode;
22

3-
import com.alibaba.fastjson.JSON;
4-
53
/**
64
* @author xun2.liu
75
* @title: Solution11
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.algorithm.study.demo.algorithm.leetcode;
2+
3+
/**
4+
* @author xun2.liu
5+
* @title: Solution24
6+
* @projectName algorithm-study
7+
* @description: 给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
8+
*
9+
* 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
10+
11+
* 示例 1:
12+
*
13+
* 给定数组 nums = [1,1,2],
14+
*
15+
* 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
16+
*
17+
* 你不需要考虑数组中超出新长度后面的元素。
18+
*
19+
* 来源:力扣(LeetCode)
20+
* 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array
21+
* @date 2020/6/10 11:33
22+
*/
23+
public class Solution24 {
24+
/**
25+
* 解法: 双指针
26+
* 首先注意数组是有序的,那么重复的元素一定会相邻。
27+
* 要求删除重复元素,实际上就是将不重复的元素移到数组的左侧。
28+
* 考虑用 2 个指针,一个在前记作 p1,一个在后记作 p2,算法流程如下:
29+
* 比较 p1 和 p2 位置的元素是否相等。
30+
* 如果相等,p2 后移 1 位
31+
* 如果不相等,将 p2 位置的元素复制到 p1+1 位置上,p1 后移一位,p2 后移 1 位
32+
* 重复上述过程,直到 p2 等于数组长度。
33+
* 返回 p1 + 1,即为新数组长度。
34+
* @param nums
35+
* @return
36+
*/
37+
public static int removeDuplicates(int[] nums) {
38+
int p1=0;
39+
int p2=0;
40+
while(p2<nums.length){
41+
//如果不相等,将 p2 位置的元素复制到 p1+1 位置上,p1 后移一位,p2 后移 1 位
42+
if (nums[p1]!=nums[p2]){
43+
p1++;
44+
nums[p1]=nums[p2];
45+
}
46+
p2++;
47+
}
48+
return p1+1;
49+
}
50+
public static void main(String[] args) {
51+
System.out.println(removeDuplicates(new int[]{0, 0, 1, 1, 3}));
52+
}
53+
}

src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution3.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package com.algorithm.study.demo.algorithm.leetcode;
22

33
import java.util.HashMap;
4-
import java.util.List;
54
import java.util.Map;
65
import java.util.PriorityQueue;
76

0 commit comments

Comments
 (0)