zoukankan      html  css  js  c++  java
  • [Leetcode]Remove Duplicates from Sorted Array & Remove Element

    No.26, Remove Duplicates from Sorted Array

    No.27, Remove Element

    第一个题是给定一个已经排序的数组,去掉里面所有重复的数字,返回新长度。

    这道题不用处理新长度之后的数组元素。那么只需要把不重复的往前面写即可,使用一个计数器看现在写到数组的哪一个位置了,每遍历到一个新数字,则将计数器向后挪一个。最后长度也就是计数器的值。

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            if(nums.empty()){
                return 0;
            }
            int lastnumber=nums[0];
            int number_point=1;
            for(int i=1;i<nums.size();i++){
                if(lastnumber!=nums[i]){
                    lastnumber=nums[i];
                    nums[number_point]=nums[i];
                    number_point++;
                }
            }
            return number_point;
        }
    };

    第二个题是给定一个数组和一个值,把数组中的该值都去掉,返回一个修改后的数组和数组长度。

    跟第一题类似,可以采用一个个遍历再写的方法。当然如果不要求顺序,也可以在效率上采用把最后的元素往前面填坑的方法。

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            if(nums.empty()){
                return 0;
            }
            int number_point=0;
            int count=0;
            for(int i=0;i<nums.size();i++){
                if(nums[i]!=val){
                    nums[number_point]=nums[i];
                    number_point++;
                    count++;
                }
            }
            return count;
        }
    };
  • 相关阅读:
    Bootstrap
    继承与多态
    面对对象与封装
    antd表格排序
    样式文本过长用...显示的时候,用弹框来显示文本(react为例)
    锚点
    树形结构的搜索,只显示搜索内容
    fetch不携带cookie
    antd 给select下拉框添加懒加载
    post方法下载文件
  • 原文地址:https://www.cnblogs.com/lilylee/p/5257944.html
Copyright © 2011-2022 走看看