去掉有序数组中重复数字 原地 leetcode java (最简单的方法)

1.利用荷兰国旗的思路,每次记住最后一个位置,遇到一个不重复的数,放在它后面,代码很简单。

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

 1 public class Solution {
 2     public int removeDuplicates(int[] A) {
 3         int len=A.length;
 4         if(len==0) return 0;
 5         int pos=0;
 6         
 7         
 8         for(int i=1;i<len;i++)
 9         {
10             if(A[i]!=A[pos])
11             {
12                 pos++;
13                 A[pos]=A[i];
14                 
15                 
16             }
17             
18             
19         }
20         return pos+1;
21         
22         
23         
24     }
25         
26 }
View Code

 2.只要跟end的前一个比较就行了,思路跟上边,就一点不一样,原创啊

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

 1 public class Solution {
 2     public int removeDuplicates(int[] A) {
 3        int len=A.length;
 4         if(len==0) return 0;
 5         if(len==1) return 1;
 6         int end=1;
 7         for(int i=2;i<len;i++)
 8         {
 9             if(A[i]!=A[end-1])
10             {
11                 end++;
12                 A[end]=A[i];
13                 
14                 
15             }
16             
17         }
18         
19         return end+1;
20         
21     }
22 }

 

 

 

 

转载于:https://www.cnblogs.com/hansongjiang/p/3834488.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值