LeetCode:27. Remove Element(Easy)

1. 原题链接

https://leetcode.com/problems/remove-element/description/

2. 题目要求

给定一个整数数组 nums[ ] 和一个整数 val,删除数组中与val相同的元素,并返回删除后的数组长度

注意:不能定义新的数组,只能使用O(1)空间大小

3. 解题思路

遍历一次,将每个元素与给定的value进行比较,不同则给nums[count++]赋予当前元素的值;相同则直接跳过,最后返回count,即为删除后数组的长度。

4. 代码实现

public class RemoveElement27 {
    public static void main(String[] args) {
        int[] nums = {2, 34, 5, 67, 89, 5, 4};
        System.out.println(removeElement(nums, 5));
    }

    public static int removeElement(int[] nums, int val) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val)
                nums[count++] = nums[i];
        }
        return count;
    }
}

  

posted @ 2017-12-31 10:55  一只敲码的猫  阅读(129)  评论(0编辑  收藏  举报