leetcode26. Remove Duplicates from Sorted Array

Posted godlei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode26. 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.

解题分析:

扫描一遍链表,用一个变量标记已找到的不重复的元素的长度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 }

 

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

[LeetCode]26. Remove Duplicates from Sorted Array

Leetcode 26. Remove Duplicates from Sorted Array

[leetcode-26-Remove Duplicates from Sorted Array]

Leetcode----26. Remove Duplicates from Sorted Array

LeetCode26. Remove Duplicates from Sorted Array

LeetCode 26. Remove Duplicates from Sorted Array