首页 > 其他 > 详细

LeetCode:27. Remove Element(Easy)

时间:2017-12-31 11:48:42      阅读:229      评论:0      收藏:0      [点我收藏+]

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;
    }
}

  

LeetCode:27. Remove Element(Easy)

原文:https://www.cnblogs.com/huiAlex/p/leetcode.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!