0
点赞
收藏
分享

微信扫一扫

26. Remove Duplicates from Sorted Array【删除排序数组中的重复项】

GhostInMatrix 2022-06-27 阅读 143

26. Remove Duplicates from Sorted Array【删除排序数组中的重复项】_i++
26. Remove Duplicates from Sorted Array【删除排序数组中的重复项】_LeetCode_02

package LeetCode;

public class Test {
public static void main(String[] args) {
int[] nums1 = {1,1,2};
System.out.println(removeDuplicates(nums1));

int[] nums2 = {0,0,1,1,1,2,2,3,3,4};
System.out.println(removeDuplicates(nums2));

}

/**
* 采用外带的变量直接去重
*/
public static int removeDuplicates(int[] nums) {
if (nums.length == 0) {
return 0;
} else if (nums.length == 1) {
return 1;
}

int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[i] != nums[j]) {
i++;
nums[i] = nums[j];
}
}

return i+1;
}
}


举报

相关推荐

0 条评论