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

【leetcode】26. Remove Duplicates from Sorted Array

时间:2016-07-05 01:10:45      阅读:230      评论: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.

解题分析:

扫描一遍链表,用一个变量标记已找到的不重复的元素的长度len,每当找到不重复元素时,就让被扫描元素与变量len标记的元素交换位置即可

具体代码:

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

 

【leetcode】26. Remove Duplicates from Sorted Array

标签:

原文地址:http://www.cnblogs.com/godlei/p/5642172.html

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