本文主要是介绍LeetCode(28)-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.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.
思路
- 题意是把有序数组的重复元素去掉,返回不重复元素的个数n,至于后面的元素怎么排列没有要求,前n个必须是不重复的元素,相对顺序不变
- 设置两个变量,一个用来存放最后一个不重复数的坐标,一个用来往下比较看是不是初夏重复
- -
代码
public class Solution {public int removeDuplicates(int[] nums) {if(nums == null){return 0;}if(nums.length == 1){return 1;}int n = nums.length;int j = 0;for(int i = 0; i < (n-1);i++){if(nums[i] != nums[i+1]){nums[j++] = nums[i];}if(i == (n-2)){nums[j] = nums[n-1];}}return (j+1);}
}
这篇关于LeetCode(28)-Remove Duplicates from Sorted Array的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!