java删除有序数组中的重复元素_Leet Code 26 删除有序数组中重复元素 - Java

给定一个有序数组,在原数组中删除重复的元素,返回新的长度。

不能新建一个数组分配额外空间,必须在原数组上进行操作。

例如:

给定输入数组 nums=[1,1,2],

你的方法需要返回新的长度等于2,新数组中前两个元素是 1 和 2。不关心数组中超过新长度部分的内容。

public class Solution {

public static int removeDuplicates(int[] nums) {

if (nums == null || nums.length == 0) {

return 0;

}

if (nums.length == 1) {

return 1;

}

int i = 0;

int j = 1;

while (i < nums.length && j < nums.length) {

while (i == 0 || i < nums.length && nums[i] > nums[i - 1]) {

i++;

}

while (i < nums.length && j < nums.length && nums[j] <= nums[i - 1]) {

j++;

}

if (i < nums.length && j < nums.length) {

if (nums[j] <= nums[i - 1]) {

break;

}

if (j != i) {

nums[i] = nums[j];

i++;

j++;

}

}

}

return i;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值