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

LeetCode OJ 26. Remove Duplicates from Sorted Array

时间:2016-05-20 00:50:47      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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.

Subscribe to see which companies asked this question

【思路】

举个例子[1,1,1,2,2,2,3,4,5],我的想法就是找到每一节重复数字的长度,然后把后面的数字向前移动,直到遍历到数组最后。

上述例子中,我们从头开始发现有1重复出现了3次,因此我们把1后面的数字向前移动2,变为[1,2,2,2,3,4,5],然后把数组的len变为len-2,重复上面的结果直到遍历到最后,代码如下:

 1 public class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         if(nums==null || nums.length==0) return 0;
 4         int len = nums.length;
 5         int duplen = 0;
 6         for(int i = 0; i < len - 1; i++){
 7             duplen = 0;
 8             for(int j = i + 1; j < len; j++){
 9                 if(nums[j] == nums[i]) duplen++;
10                 else break;
11             }
12             if(duplen > 0){
13                 for(int k = i + duplen + 1; k < len; k++){
14                     nums[k-duplen] = nums[k];
15                 }
16                 len = len - duplen;
17             }
18         }
19         return len;
20     }
21 }

 

LeetCode OJ 26. Remove Duplicates from Sorted Array

标签:

原文地址:http://www.cnblogs.com/liujinhong/p/5510663.html

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