Remove Element

问题描述:

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

Do not allocate extra space for another array, you must do this in place with constant memory.

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

Example:
Given input array nums = [3,2,2,3]val = 3

Your function should return length = 2, with the first two elements of nums being 2.

 

解答:

package array;

import java.util.Arrays;

public class RemoveValueDemo {
    public static void main(String[] args) {
        int[] nums1 = {1, 1, 2, 2, 3};
        int length = removeValue(nums1, 1);
        print(length);

        int[] nums2 = new int[length];
        System.arraycopy(nums1, 0, nums2, 0, length);
        print(Arrays.toString(nums2));
    }

    public static int removeValue(int[] nums, int val) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        int idx = 0;
        for(int num: nums) {
            if(num != val) {
                nums[idx++] = num;
            }
        }
        return idx;
    }

    public static void print(Object obj) {
        System.out.println(obj);
    }
}
def remove_val(nums, val):
    if not nums:
        return 0
    idx = 0
    for num in nums:
        if num != val:
            nums[idx] = num
            idx += 1
    return idx

nums = [1, 1, 2, 2, 3, 4, 5, 5]
l = remove_val(nums, 3)
print l, nums[:l]

猜你喜欢

转载自economist.iteye.com/blog/2346753