#力扣:26. 删除有序数组中的重复项@FDDLC

26. 删除有序数组中的重复项

一、Java

class Solution {
    public int removeDuplicates(int[] nums) {
        int l = 0;
        for (int i = 0; i < nums.length; nums[l++] = nums[i++]) {
            while (i + 1 < nums.length && nums[i] == nums[i + 1]) i++;
        }
        return l;
    }
}
class Solution {
    public int removeDuplicates(int[] nums) {
        int slow = 0;
        for (int fast = 1; fast < nums.length; fast++) {
            if (nums[slow] != nums[fast]) nums[++slow] = nums[fast];
        }
        return slow + 1;
    }
}

二、C++

#include 
using namespace std;
class Solution {
public:
    int removeDuplicates(vector& nums) {
        int slow = 0;
        for (int fast = 1; fast < nums.size(); fast++) {
            if (nums[slow] != nums[fast]) nums[++slow] = nums[fast];
        }
        return slow + 1;
    }
};

三、Python

from typing import List
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        slow = 0
        for fast in range(1, len(nums)):
            if nums[slow] != nums[fast]:
                slow += 1
                nums[slow] = nums[fast]
            fast += 1
        return slow + 1

四、JavaScript

var removeDuplicates = function (nums) {
    let slow = 0;
    for (let fast = 1; fast < nums.length; fast++) {
        if (nums[slow] != nums[fast]) nums[++slow] = nums[fast];
    }
    return slow + 1;
};

五、Go

package main

func removeDuplicates(nums []int) int {
	slow := 0
	for fast := 1; fast < len(nums); fast++ {
		if nums[slow] != nums[fast] {
			slow++
			nums[slow] = nums[fast]
		}
	}
	return slow + 1
}

你可能感兴趣的:(力扣刷题:Java,C++,Python,JS,Go,leetcode,算法,数据结构)