zoukankan      html  css  js  c++  java
  • 【LeetCode】27

    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.

    Solution 1:

    int removeElement(vector<int>& nums, int val)
    {
       /*set a new indexto to record new length, if it is val then jump to next element and do nothing,
        else, keep it. But there are some redundant assignment*/
    if(nums.empty())return 0; int length=0; for(int i=0;i<nums.size();i++) { if(nums[i]!=val) nums[length++]=val; } return length; }

    Solution 2:

    int removeElement(vector<int>& nums, int val)
    {
       /*the most beautiful solution, when it meets val, assignment this position with the last element, it cost less than once tranversal
        Tips: the element from the last may be val, so i-- is necessary*/
    if(nums.empty())return 0; int newlength=nums.size(); for(int i=0;i<newlength;i++) { if(nums[i]==val) { nums[i]=nums[newlength-1]; i--; newlength--; } } return newlength; }
  • 相关阅读:
    下载文件
    全局处理程序
    缩略图
    图片
    文件上传
    application用法
    多分辨率的支持
    适用于cocos2dx的编辑器:Texture,Tilemap,Particle,Action,Level etc
    cocos2dx下最大纹理大小取决于平台
    CCLabelTTF 如何支持换行符和换行
  • 原文地址:https://www.cnblogs.com/irun/p/4716541.html
Copyright © 2011-2022 走看看