• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
MKT-porter
博客园    首页    新随笔    联系   管理    订阅  订阅
reLeetCode 热题 100-1 指针283. 移动零

 

 

 

 

image

 

class Solution {
public:
    void moveZeroes(vector<int>& nums) {

      
    //   int cout_=0;

    //   for(int i =0; i<nums.size();i++){
    //     if(nums[i]==0){
    //         cout_++;
    //     }
    //   }
    // std::cout<< " 0's all num: " << cout_ << std::endl;
      int temp_cout=0;
      int L=nums.size();
      for(int i =0; i<L-temp_cout;i++){

        if(nums[i]==0){
            temp_cout=temp_cout+1;
            int j =i;
            while(j<(L-1)){
              nums[j]=nums[j+1];
              j++;
            }
            i=i-1;
            nums[L-temp_cout]=0;
        }
        
      }

    //   for(int i=nums.size()-temp_cout;i<nums.size();i++){

    //     //  std::cout<< " set 0's idex: " <<  i <<"/ 总数目"<< nums.size() <<std::endl;
    //       nums[i]=0;
    //   }

  
      

    }
};

  

image

 

 

class Solution {
public:
    void moveZeroes(vector<int>& nums) {


    int *qian = &nums[0];// 
    int *hou = &nums[1];// 元素访问使用&
    int *end = &nums[nums.size()-1];
    int i=0;
    while(qian<end)  {
        if(*qian==0){
            while(hou<=end){
             if(*hou!=0){
                swap(*qian,*hou);
                break;
             }  
             else{
                hou++;

             }
           }
        }
        qian++;
        hou=qian+1;
        
    }

    }
};

官方改自己的

image

 

class Solution {
public:
    void moveZeroes(vector<int>& nums) {


    int *qian = &nums[0];// 
    int *hou = &nums[0];// 元素访问使用&
    int *end = &nums[nums.size()-1];
    
    while(hou<=end)  {
        if(*hou!=0){
            swap(*qian,*hou);
            qian++;
        }
        hou++;
       
        
    }


        // int n = nums.size(), left = 0, right = 0;
        // while (right < n) {
        //     if (nums[right]) {
        //         swap(nums[left], nums[right]);
        //         left++;
        //     }
        //     right++;
        // }



    }
};

  

 官方

但是没用到指针啊

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int n = nums.size(), left = 0, right = 0;
        while (right < n) {
            if (nums[right]) {
                swap(nums[left], nums[right]);
                left++;
            }
            right++;
        }
    }
};

作者:力扣官方题解
链接:https://leetcode.cn/problems/move-zeroes/solutions/489622/yi-dong-ling-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  

 

posted on 2025-09-15 18:46  MKT-porter  阅读(7)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3