zoukankan      html  css  js  c++  java
  • 27. Remove Element

    问题:

    删除数组中的元素val。

    返回剩下数组的size。

    Example 1:
    Input: nums = [3,2,2,3], val = 3
    Output: 2, nums = [2,2]
    Explanation: Your function should return length = 2, with the first two elements of nums being 2.
    It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted.
    
    Example 2:
    Input: nums = [0,1,2,2,3,0,4,2], val = 2
    Output: 5, nums = [0,1,4,0,3]
    Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.
     
    Constraints:
    0 <= nums.length <= 100
    0 <= nums[i] <= 50
    0 <= val <= 100
    

      

    解法:slow-fast pointers(快慢指针)

    • 0~slow-1:满足题意的数组。
    • fast:探测是否存在非val的值。
      • 如果 是非val:将fast指向的值加入前面满足题意的数组中,将不满足的slow放到后面。
      • swap(slow, fast)
      • slow++
    • 继续下一个探测fast++

    代码参考:

     1 class Solution {
     2 public:
     3     int removeElement(vector<int>& nums, int val) {
     4         int n=nums.size();
     5         int i=0, j=0;
     6         if(n==0) return 0;
     7         while(j<n) {
     8             if(nums[j]!=val) {
     9                 swap(nums[i], nums[j]);
    10                 i++;
    11             }
    12             j++;
    13         }
    14         return i;
    15     }
    16 };
  • 相关阅读:
    什么时候是个头?
    生活就是这样
    差距究竟在哪里?
    认识到三个问题
    研究生三件事
    重写DNN6.2注册、登陆、修改等个人中心
    SQL游标的使用
    SQL UPDATE实现多表更新
    SQL 百万级两表数据间更新和添加
    DNN路径
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14627478.html
Copyright © 2011-2022 走看看