首页 > 其他 > 详细

【Leetcode】27. Remove Element

时间:2017-07-16 18:00:27      阅读:236      评论:0      收藏:0      [点我收藏+]

Question:

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.

 

题目说明:

输入一个int类型数组:nums = [3,2,2,3]

以及一个数组内的数字:val = 3

要求输出去除val之后数组长度,并且数组要将所有val覆盖掉;

 

SHOW YOU THE CODE

 

 1 package easy;
 2 
 3 public class L27 {
 4     // Remove Element
 5     public int removeElement(int[] nums, int val) {
 6         int ans;
 7         int len = nums.length;
 8         ans = len;
 9         int count = 0;
10         for (int i = 0; i < len; i++) {
11             if (nums[i] == val) {
12                 ans--;
13 
14             } else {
15                 nums[count] = nums[i];
16                 count++;
17             }
18         }
19         for (int i = 0; i < count; i++) {
20             System.out.println(nums[i]);
21         }
22         System.out.println(ans);
23         return ans;
24     }
25 
26     public static void main(String[] args) {
27         L27 l27 = new L27();
28         int[] nums = { 2, 2, 2, 2, 3 };
29         int val = 3;
30         l27.removeElement(nums, val);
31     }
32 }

 

注:

①题目说明需要改变原数组,将val覆盖掉:

        else {
                nums[count] = nums[i];
                count++;
            }

这段代码中count记录除去val之后的数字个数,可以覆盖掉原来数组

②写给你看看,今天的代码写的超级爽快,10几分钟 oh yeah

 

【Leetcode】27. Remove Element

原文:http://www.cnblogs.com/yumiaomiao/p/7191144.html

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