• 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

  • 相关阅读:
    226. 翻转二叉树
    LeetCode 1660.纠正二叉树(Medium)
    814. 二叉树剪枝
    110. 平衡二叉树
    HTTPS原理浅析
    MySQL知识网络
    制作SSL证书(签发免费证书)
    Redis高可用三(Redis Cluster集群)
    Redis高可用二( 哨兵sentinel)
    Redis高可用一(主从)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7163914.html
Copyright © 2020-2023  润新知