Remove Duplicates from Sorted Array

来源:互联网 发布:java编程思想视频全集 编辑:程序博客网 时间:2024/06/06 02:49

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.


需要注意几点:

1.输入的是已排序的数组;

2.不可再申请额外空间;

3.数组中元素的位置不能改变。比如对于数组[1,1,1,4,5],移除重复元素后为[1,4,5],起始数字为1,而不能是其它数字。


package leetcode;



public class RemoveDuplicatesFromSortedArray {

public staticint removeDuplicates(int[] nums) {

        int ans = nums.length;

        if (ans == 0 ||ans == 1) return ans;

        int index = 1;

        for (int i = 1; i<nums.length;i++){

        if (nums[i] ==nums[i-1]){

        continue;

        }else{

        nums[index] =nums[i];

        index++;

        }

        }

        return index;

    }


public staticvoid main(String[] args) {

// TODO Auto-generated method stub

int[] nums = {1,1,2};

System.out.println(removeDuplicates(nums));

}


}


0 0
原创粉丝点击