首页 > 其他 > 详细

Remove Duplicates from Sorted Array

时间:2016-07-01 09:00:06      阅读:238      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!