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

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 }
不积跬步无以至千里,千里之堤毁于蚁穴。 你是点滴积累成就你,你的丝丝懒惰毁掉你。 与诸君共勉
原文地址:https://www.cnblogs.com/haoHaoStudyShare/p/7360394.html