您的位置:首页
LeetCode(28)-Remove Duplicates from Sorted Array
2017-08-18 17:58
274 查看
题目:
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
- LeetCode(28)-Remove Duplicates from Sorted Array
- LeetCode(28)-Remove Duplicates from Sorted Array
- [leetcode 28] Remove Duplicates from Sorted Array
- LeetCode(28)-Remove Duplicates from Sorted Array
- leetcode_Remove Duplicates from Sorted Array
- [LeetCode] Remove Duplicates from Sorted Array II 有序数组中去除重复项之二
- leetcode80 Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode(80) Remove Duplicates From Sorted Array II
- LeetCode-26&80.Remove Duplicates from Sorted Array
- 【Leetcode】26. Remove Duplicates from Sorted Array
- [LeetCode] Remove Duplicates from Sorted Array
- [LeetCode][Java] Remove Duplicates from Sorted Array
- Leetcode 26 Remove Duplicates from Sorted Array
- leetcode 35: Remove Duplicates from Sorted Array
- LeetCode() Remove Duplicates from Sorted Array II
- Leetcode NO.80 Remove Duplicates from Sorted Array II
- LeetCode—Remove Duplicates from Sorted Array
- LeetCode-Remove Duplicates from Sorted Array II