zoukankan      html  css  js  c++  java
  • 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.

    思路:

    核心的代码是这样的。k一开始为0,保存第一个数据到val,i从1开始,如果此时num的数据是val值,不进行任何操作,如果不是,那么先不k+1,保存到num[k]里面,然后k+1。

    代码:

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


  • 相关阅读:
    排座椅
    关于math.h的问题
    客户调查
    排队打水
    删数游戏
    小数背包
    零件分组
    桐桐的组合
    桐桐的数学游戏
    桐桐的全排列
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519894.html
Copyright © 2011-2022 走看看