首页 > 其他 > 详细

【leetcode】26. Remove Duplicates from Sorted Array

时间:2016-07-05 01:08:35      阅读:199      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!