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

  • 相关阅读:
    MySQL 日志管理
    nginx 日志分割
    Canvas 动态小球重叠效果
    Canvas制作动态进度加载水球
    js 多张爆炸效果轮播图
    js 多张图片加载 环形进度条
    INSTALL_FAILED_CONFLICTING_PROVIDER
    安卓 文件管理器 各种应用 源码
    android 静音
    android studio 查看大纲
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7163914.html
Copyright © 2011-2022 走看看