leetcode-Remove Duplicates from Sorted Array

Posted 8亩田

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-Remove Duplicates from Sorted Array相关的知识,希望对你有一定的参考价值。

question:Remove Duplicates from Sorted Array

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

技术分享图片
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
中文

 

Example 1:

Given 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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn‘t matter what values are set beyond the returned length.

Link:https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/

 思路:

理解1:定义两个索引,一个头索引,一个尾索引,头索引指向找到的数(也是刚被移动的数),尾索引找不相同的数;比如 [1,1,2],

经过循环后;end=2,head=1;

理解2:一个快指针,一个慢指针,慢指针的下标是快指针找到不相同的元素移动到数组的那个位置的下标;(同样也是不重复元素的个数)

class Solution {
    public int removeDuplicates(int[] nums) {
       int head=0 ,end=0;
        /**
        定义一个头索引和一个尾索引,头索引指向刚被移动的数.尾索引找不相同的数,
        并且移动到头索引的下下一个
        
        */
    	
    	for (int i = 0; i < nums.length; i++) {
    		
    		if(nums[head]!=nums[end]){
    			nums[head+1]=nums[end];
    			head++;
    			
    		}
			end++;
		}
        
        return head+1;
        
    }
}

 

 

以上是关于leetcode-Remove Duplicates from Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Remove Invalid Parentheses

LeetCode-Remove Linked List Elements

leetcode-Remove Duplicates from Sorted Array

LeetCode-Remove Duplicates from Sorted Array II

leetcode-Remove Duplicates from Sorted Array II-80

Contains Duplicate,Contains Duplicate II,Contains Duplicate III