关于java:LeetCode026删除有序数组中的重复项

删除有序数组中的反复项

题目形容:给你一个有序数组 nums ,请你 原地 删除反复呈现的元素,使每个元素 只呈现一次 ,返回删除后数组的新长度。

不要应用额定的数组空间,你必须在 原地 批改输出数组 并在应用 O(1) 额定空间的条件下实现。

示例阐明请见LeetCode官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:数组的遍历
  • 首先,如果数组nums为空或者数组nums的长度为0,间接返回0;
  • current记录以后不反复的索引地位,遍历数组,pre记录上一位的值,当以后位index的值和pre的值相等时,index+1后往后持续遍历;当以后位的值和pre的值不相等时,更新current的值为以后index位的值,并且将current往后移一位,index+1,pre不停的往后移,直到遍历完结地位。
public class LeetCode_026 {
    public static int removeDuplicates(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int current = 1;
        int index = 1;
        int pre = nums[0];
        while (index < nums.length) {
            if (!(nums[index] == pre)) {
                nums[current++] = nums[index];
            }
            pre = nums[index];
            index++;
        }
        return current;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
        int result = removeDuplicates(nums);
        System.out.println(result);
        for (int num : nums) {
            System.out.print(num + " ");
        }
    }
}

【每日寄语】 纵有千古,横有八荒;前途似海,来日方长。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理