码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:27. Remove Element(Easy)

时间:2017-12-31 11:59:36      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:不能   value   数组   return   rgs   href   blank   target   定义   

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)

标签:不能   value   数组   return   rgs   href   blank   target   定义   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!