【leetcode】26. Remove Duplicates from Sorted Array

来源:互联网 发布:dreamweaver破解版mac 编辑:程序博客网 时间:2024/06/05 06:20

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.

已知一个已经排好序的数组,将重复的元素移除并且返回重新整理后数组的长度。

考虑的问题://数组一旦创建出来数组大小就不可改变,如{1, 2, 2, 3, 3}会变成{1, 2, 3, 3, 3}

这道题目是跟 数组 相关的问题,解决这类问题,最好使用交换,效率比较高

//26. Remove Duplicates from Sorted Arraypublic int removeDuplicates(int[] nums) {if(nums.length < 2)return nums.length;int a = 1;int b = 0;while(a < nums.length){if(nums[a] == nums[b]){a++;}else{b++;nums[b] = nums[a];a++;}}return b+1;    }


0 0
原创粉丝点击