(LeetCode 面试经典 150 题 ) 27. 移除元素 (双指针)

题目:27. 移除元素

(LeetCode 面试经典 150 题 ) 27. 移除元素 (双指针)_第1张图片
(LeetCode 面试经典 150 题 ) 27. 移除元素 (双指针)_第2张图片

思路:双指针,时间复杂度0(n)。

左指针i左边的都是不等于val的值,右指针j右边都是等于val的值。

C++版本:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int i=0,j=nums.size()-1;
        while(i<=j){
            if(nums[i]==val){
                nums[i]=nums[j];
                j--;
            }else{
                i++;
            }
        }
        return i;
    }
};

JAVA版本:

class Solution {
    public int removeElement(int[] nums, int val) {
        int i=0,j=nums.length-1;
        while(i<=j){
            if(nums[i]==val){
                nums[i]=nums[j];
                j--;
            }else{
                i++;
            }
        }
        return i;
    }
}

Go版本:

func removeElement(nums []int, val int) int {
    i,j:=0,len(nums)-1
    for i<=j {
        if nums[i]==val {
            nums[i]=nums[j]
            j--
        }else{
            i++
        }
    }
    return i
}

你可能感兴趣的:(C++,JAVA,Go版本,LeetCode,LeetCode,面试经典,150,题,leetcode,面试,算法,java,go,c++)