LeetCode 26. Remove Duplicates from Sorted Array (从有序序列里移除重复项)

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 nums = [1,1,2],

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 new length.

 

 


题目标签:Array
  这道题目给了我们一个有序array, 让我们把重复的都移除,并且要求我们不能利用额外的空间,只能在原有的array里改。这里需要两个pointers, i 和 j。 设置j 为0, i 从1 开始遍历。目的是让i 找到一个不重复的数字,一旦找到,我们把这个数字放在j 的后面一个位子。这样的话,所有重复的数字,都会放在j后面。j之前的包括j的部分都是不重复的。最后只要return j+1 就可以了。
 
 

Java Solution:

Runtime beats 55.60% 

完成日期:03/09/2017

关键词:Array

关键点:利用two pointers

 

 1 public class Solution 
 2 {
 3     public int removeDuplicates(int[] nums) 
 4     {
 5         // check validation.
 6         if(nums.length == 0)
 7             return 0;
 8         
 9         
10         int j = 0;
11         
12         // iterate nums array.
13         for(int i=1; i<nums.length; i++)
14         {
15             // once find the nums[i] that doesn't match nums[j]
16             if(nums[i] != nums[j])
17             {
18                 j++;
19                 // swap the non-duplicate one with duplicate one or with itself
20                 nums[j] = nums[i];
21             }
22             
23         }
24         
25         return j+1;
26     }
27 }

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

转载于:https://www.cnblogs.com/jimmycheng/p/7163888.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值