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

[Leetcode]26. Remove Duplicates from Sorted Array

时间:2017-10-24 22:29:37      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:ica   pac   dex   i+1   moved   cat   一个   input   sort   

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.

 

思路:

  (1)虽然能AC,但是不对的思路:如果找到重复的数,就将其设置成一个很大的数,最后再排序一下,返回新的长度。

 1 class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         if (nums.length<=1)
 4             return nums.length;
 5         int duplicate = 0;
 6         for (int i=0;i<nums.length-1;i++){
 7             if (nums[i]==nums[i+1]){
 8                 nums[i]=123456;
 9                 duplicate++;
10             }
11         }
12         Arrays.sort(nums);
13         return nums.length-duplicate;
14     }
15 }

  (2)正常的思路:如果有重复的元素,就跳过,然后把后面元素的值赋在重复的位置上

 1 class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         if (nums.length<=1)
 4             return nums.length;
 5         int index = 0;
 6         for (int i=1;i<nums.length;i++){
 7             if (nums[i]!=nums[index]){
 8                 index++;
 9                 nums[index]=nums[i];
10             }
11         }
12         return index+1;
13     }
14 }

 

[Leetcode]26. Remove Duplicates from Sorted Array

标签:ica   pac   dex   i+1   moved   cat   一个   input   sort   

原文地址:http://www.cnblogs.com/David-Lin/p/7725828.html

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