26. Remove Duplicates from Sorted Arrayleetcode,数组,array,java,算法
Posted 皓浩浩皓
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了26. Remove Duplicates from Sorted Arrayleetcode,数组,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 }
以上是关于26. Remove Duplicates from Sorted Arrayleetcode,数组,array,java,算法的主要内容,如果未能解决你的问题,请参考以下文章
26. Remove Duplicates from Sorted Array
26. Remove Duplicates from Sorted Array
#26 Remove Duplicates from Sorted Array
LeetCode OJ 26. Remove Duplicates from Sorted Array
leetcode 26. Remove Duplicates from Sorted Array 80. Remove Duplicates from Sorted Array II