zoukankan      html  css  js  c++  java
  • LeetCode 27. Remove Element (移除元素)

    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.


    题目标签:Array
      这道题目给了我们一个nums array, 让我们把array 里和val 相同的数字都移除,最后return 一个 新的length。题目规定我们要in place。 所以利用two pointers, i 和 res = 0。 让 i 从0 开始遍历,一旦找到和val 不相同的数字,把这个数字和res 位置的数字互换,res++。意思就是,把所有不需要删除的数字,放到前面去。res记录了所有不需要删除的数字。
     
     

    Java Solution:

    Runtime beats 95.05% 

    完成日期:03/27/2017

    关键词:Array

    关键点:Two Pointers

     1 public class Solution 
     2 {
     3     public int removeElement(int[] nums, int val) 
     4     {
     5         int res = 0; // count non-val numbers
     6         
     7         for(int i=0; i<nums.length; i++)
     8             if(nums[i] != val) // once find the non-val number, swap non-val number with res index
     9                 nums[res++] = nums[i];
    10                 
    11         return res;
    12     }
    13 }

    参考资料:

    http://www.cnblogs.com/grandyang/p/4606700.html

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    网页设计 【0834】
    Apache Commons Lang
    Arduino U8G2 OLED_SSD1306_Chart
    Arduino Adafruit_SSD1306的使用
    proteus pro 8.9 安装及汉化教程
    AD IC类元件模型的创建
    C/C++ 深入理解char * ,char ** ,char a[ ] ,char *a[] 的区别
    Arduino MLX90614
    Arduino uno mega2560
    C语言 堆和栈
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7163914.html
Copyright © 2011-2022 走看看