LC.80.Remove Duplicates from Sorted Array II

https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/

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

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

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3.
It doesn't matter what you leave beyond the new length.

 1 public int removeDuplicates(int[] nums) {
 2         if (nums == null || nums.length <= 2){
 3             return nums.length ;
 4         }
 5 
 6         //slow pointer: 启示的位置 从2开始
 7         int slow = 2 ;
 8         //fast pointer
 9         /*                                s
10                              2    2   3
11                     1,  1,   1,   2,  2,  3
12                                               i
13         * */
14         for (int i = 2; i < nums.length; i++) {
15             if (nums[slow-2] != nums[i]){
16                 nums[slow++] = nums[i];
17             }
18         }
19         return slow;
20     }

 

posted @ 2018-04-16 23:52  davidnyc  阅读(129)  评论(0编辑  收藏  举报