您的位置:首页 > 其它

LeetCode 26 Remove Duplicates from Sorted Array (移除有序数组中重复数字)

2017-03-09 19:38 549 查看
题目链接: https://leetcode.com/problems/remove-duplicates-from-sorted-array/?tab=Description

从有序数组中移除重复数字,并且返回不重复数字的个数

遍历操作: 可以使用新的for循环 for (int n : nums){}

每次进行对比,并且更新第一个遇到不相等的元素的下标为i
对数组进行重新赋值操作

当数组长度大于1时,ans初值为1,当数组长度为0时,返回0

参考代码 :

package leetcode_50;

/***
*
* @author pengfei_zheng
* 移除有序数组中的重复元素
*/
public class Solution26 {
public int removeDuplicates(int[] nums) {
if(nums.length==0) return 0;
int i = 1;

for (int n : nums)
if (n > nums[i-1])//满足则说明不重复
nums[i++] = n;//更新i
return i;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐