码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted Array

时间:2016-07-01 09:02:15      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

Remove Duplicates from Sorted Array I

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.

Example

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

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

分析:

用指针p指向第一个数,然后用另一个指针i 指向第二个数,如果p和i所指的数一样,把i往下移动,如果不同,把i所指的数放在p+1的位置。

 1 public class Solution {
 2     /**
 3      * @param A: a array of integers
 4      * @return : return an integer
 5      * cnblogs.com/beiyeqingteng/
 6      */
 7     public int removeDuplicates(int[] nums) {
 8         if (nums == null || nums.length == 0) return 0;
 9         
10         int p = 0;
11         for (int i = 1; i < nums.length; i++) {
12             if (nums[i] != nums[p]) {
13                 p++;
14                 nums[p] = nums[i];
15             } 
16         }
17         return p + 1;
18     }
19 }

 

Remove Duplicates from Sorted Array II

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].

分析:解题思路和上面一样,用duplicateCount 来keep track 一个数字重复出现的次数。

 1 public class Solution {
 2     /**
 3      * @param A: a array of integers
 4      * @return : return an integer
 5      * 转载请注明出处:cnblogs.com/beiyeqingteng/
 6      */
 7      
 8     public int removeDuplicates(int[] nums) {
 9         if (nums == null || nums.length == 0) return 0;
10         
11         int duplicateCount = 1;
12         int p = 0;
13         for (int i = 1; i < nums.length; i++) {
14             if (nums[i] == nums[p]) {
15                 if (duplicateCount < 2) {
16                     duplicateCount++;
17                     p++;
18                     nums[p] = nums[i];
19                 } 
20             } else {
21                 duplicateCount = 1;
22                 p++;
23                 nums[p] = nums[i];
24             }
25         }
26         return p + 1; 
27     }
28 }

转载请注明出处:cnblogs.com/beiyeqingteng/

Remove Duplicates from Sorted Array

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5631821.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!