27. Remove Element

题目:

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

链接: http://leetcode.com/problems/remove-element/

题解: 数组去除指定元素。 Time Complexity - O(n), Space Complexity - O(1)

public class Solution {
    public int removeElement(int[] A, int elem) {
        if(A == null || A.length == 0)
            return 0;
        int count = 0;
        
        for(int i = 0; i < A.length; i++){
            if(A[i] != elem)
                A[count ++] = A[i];
        }
        
        return count;
    }
}

 

二刷:

跟上一题基本一样。

Java:

public class Solution {
    public int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int index = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                nums[index++] = nums[i];
            }
        }
        return index;
    }
}

 

三刷:

判断当前元素是否等于 val,假如不等于,则赋值给num[index],并且index++。合起来写就是num[index++] = nums[i],

Java:

Time Complexity - O(n), Space Complexity - O(1)

public class Solution {
    public int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int index = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                nums[index++] = nums[i];
            }
        }
        return index;
    }
}

 

Golang

func removeElement(nums []int, val int) int {
    idx := 0
    
    for i := range nums {
        if nums[i] != val {
            nums[idx] = nums[i]
            idx++
        }
    }
    
    return idx
}
posted @ 2015-04-17 15:29  YRB  阅读(304)  评论(0编辑  收藏  举报