• 【Leetcode】27. Remove Element


    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

  • 相关阅读:
    MyEclipse添加XML的xsd文件和dtd文件(自动补全xml节点代码)
    浅析Java中Map与HashMap,Hashtable,HashSet的区别(转载)
    jsp中:jsp声明与jsp脚本<%! int count=0;%> 与<% int count=0;%>
    JSP内置对象详细介绍(上)<转载>
    学习运用json
    win7与win7之间无法访问共享文件的问题解决(转)
    关于工作情绪化的问题
    Hadoop配置学习
    问题汇总
    mysql读写分离
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/7191144.html
Copyright © 2020-2023  润新知