删除排序数组中的重复项

概述

给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。

不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。

示例

示例 1:

输入:nums = [1,1,2]
输出:2, nums = [1,2]
解释:函数应该返回新的长度 2 ,并且原数组 nums 的前两个元素被修改为 1, 2 。不需要考虑数组中超出新长度后面的元素。

-------------------------------------
示例 2:

输入:nums = [0,0,1,1,1,2,2,3,3,4]
输出:5, nums = [0,1,2,3,4]
解释:函数应该返回新的长度 5 , 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4 。不需要考虑数组中超出新长度后面的元素。

代码

	public static void main(String[] args) {
		int[] nums = {0,0,1,1,1,2,2,3,3,4,4,5,5,5};
//		[0, 1, 2, 3, 4, 5, 2, 3, 3, 4, 4, 5, 5, 5]
//		System.out.println(nums.length);
		Test01 test01 = new Test01();
		int count = test01.removeDuplicates(nums);
		System.out.println(count);
	}
	
	public int removeDuplicates(int[] nums) {
		int j = 0;
		for(int i = 0; i < nums.length; i ++){
			if(i == nums.length - 1){
				nums[j] = nums[i];
				break;
			}
			if(nums[i] != nums[i + 1]){
				nums[j] = nums[i];
				j ++;
			}
		}
//		System.out.println(Arrays.toString(nums));
		return ++ j;
    }

题目来自于:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2gy9m/

posted @ 2021-12-16 14:11  卡卡罗特琪琪  阅读(33)  评论(0编辑  收藏  举报