80. Remove Duplicates from Sorted Array II

不定期更新leetcode解题java答案。

采用pick one的方式选择题目。 

题意为将一个有序数组除去相同数字超过两个以上的元素。并返回剩余所取数量。

如:[1,2,2,2,3],因为元素2有3个,应除去一个,返回[1,2,2,3,X],长度为4(X为任意数字,理论来讲这里为3)。

思路为依次向后检验做基本处理,如下代码所示:

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

也可将多余代码省去,修改如下:

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

 

posted @ 2016-09-30 23:48  zslhq~  阅读(122)  评论(0编辑  收藏  举报