zoukankan      html  css  js  c++  java
  • [LeetCode]13. Remove Element移除元素

    Given an array and a value, remove all instances of that value in place and return the new length.

    The order of elements can be changed. It doesn't matter what you leave beyond the new length.

    解法1:先遍历数组统计出数组中含有多少个指定元素,然后遍历数组,从头开始找第一个出现指定值的位置,从尾开始找第一个不是指定元素的位置,然后覆盖指定元素即可。

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            int n = nums.size();
            int cnt = 0;
            for (int i = 0; i < n; i++)
            {
                if (nums[i] == val)
                    cnt++;
            }
            int k = 0, j = n - 1;
            while (k < j)
            {
                while (k < n && nums[k] != val)
                    k++;
                while (j >= 0 && nums[j] == val)
                    j--;
                if (k < j)
                    nums[k] = nums[j];
                k++;
                j--;
            }
            return n - cnt;
        }
    };

    解法2:设置计数器cnt=0;从头开始扫描数组,如果找到非指定值的元素,则将其覆盖计数器位置元素,然后计数器自增。此时计数器累计的是非指定元素的个数。

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            int n = nums.size();
            int cnt = 0;
            for(int i = 0; i < n; i++)
            {
                if(nums[i] != val)
                    nums[cnt++] = nums[i];
            }
            return cnt;
        }
    };
  • 相关阅读:
    Java openrasp学习记录(一)
    Java ASM3学习(3)
    Java ASM3学习(2)
    Java Instrumentation插桩技术学习
    Java ASM3学习(1)
    从JDK源码学习HashSet和HashTable
    从JDK源码学习HashMap
    从JDK源码学习ArrayList
    Java XXE漏洞典型场景分析
    CVE-2020-7961 Liferay Portal 复现分析
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4856874.html
Copyright © 2011-2022 走看看