计蒜客挑战难题:移除数组中的重复元素

来源:互联网 发布:ubuntu安装播放器 编辑:程序博客网 时间:2024/06/09 19:14

给定一个升序排列的数组,去掉重复的数,并返回新的数组的长度。

例如:

数组A = {1, 1, 2},你的函数应该返回长度2,新数组为{1, 2}

要求:

不能新开数组分配额外的空间。即常数空间限制。

提示:

输入一个整数n,以及其对应的数组A[n],输出新数组长度

样例输入

5
0 0 1 1 2
样例输出

3

代码:

import java.util.Scanner;public class Main{    public static void main(String args[]){        Scanner sc = new Scanner(System.in);        int n = sc.nextInt();        int[] A = new int[n];        for(int x = 0; x < n; x++){            A[x] = sc.nextInt();        }        int length = n;        for(int i = 0; i < n-1; i++){                if(A[i]==A[i+1])                    --length;        }        System.out.println(length);    }}
0 0
原创粉丝点击