码迷,mamicode.com
首页 > 编程语言 > 详细

26. Remove Duplicates from Sorted Array【leetcode】,数组,array,java,算法

时间:2017-08-14 23:43:40      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:设置   题意   public   blog   leetcode   should   remove   color   ted   

26. Remove Duplicates from Sorted Array

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.

题意:

给定一个数组nums[],计算其去除重复数据后的长度(不开新的内存空间)

解题思路:

设置两个标志位left=0;right=1

使用left和right进行对比,如果相同则跳过right继续,如果不相同则把right放到left的位置

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

 

26. Remove Duplicates from Sorted Array【leetcode】,数组,array,java,算法

标签:设置   题意   public   blog   leetcode   should   remove   color   ted   

原文地址:http://www.cnblogs.com/haoHaoStudyShare/p/7360394.html

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