• LeetCode: 283 Move Zeroes(easy)


    题目:

    Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

    For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

    Note:

    1. You must do this in-place without making a copy of the array.
    2. Minimize the total number of operations.

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    代码:

    不知道为什么,在本地可以运行,提交上去显示 Submission Result: Runtime Error ,感觉可能是越界?不知道。。调不出来了。。(把0和后面非0的交换)

     1 class Solution {
     2 public:
     3     vector<int> moveZeroes(vector<int>& nums) {
     4         for(auto zero = nums.begin(); zero < nums.end(); zero++){
     5             if ( *zero == 0 ){
     6                 auto notzero = zero;
     7                 for(notzero; notzero < nums.end(); notzero++){
     8                     if(*notzero != 0)
     9                         break;
    10                 }  
    11         if (zero != notzero) 12 iter_swap(zero, notzero); 13 } 14 } 15 return nums; 16 } 17 };

    换个思路(把后面非0的元素和前面的0元素交换):

     1 class Solution {
     2 public:
     3     void moveZeroes(vector<int>& nums) {
     4         int last = 0, cur = 0;
     5         while(cur < nums.size()) {
     6             if(nums[cur] != 0) {
     7                 swap(nums[last], nums[cur]);
     8                 last++;
     9             }
    10             cur++;
    11         }  
    12     }
    13 };

    别人的代码:

     1 class Solution {
     2 public:
     3     void moveZeroes(vector<int>& nums) {
     4         int nonzero = 0;
     5         for(int n:nums) {
     6             if(n != 0) {
     7                 nums[nonzero++] = n;
     8             }
     9         }
    10         for(;nonzero<nums.size(); nonzero++) {
    11             nums[nonzero] = 0;
    12         }
    13     }
    14 };
  • 相关阅读:
    在linux系统安装tomcat后,bin文件下startup.sh启动不
    利用教育邮箱注册JetBrains产品(pycharm、idea等)的方法
    linux 查看当前系统版本号
    windows 重装系统
    linux rpm方式安装mysql
    官网下载MySQL最新版本的安装包
    Redis随笔
    八大排序算法的java实现
    XML的两种解析方式
    Quartz快速入门
  • 原文地址:https://www.cnblogs.com/llxblogs/p/7482165.html
Copyright © 2020-2023  润新知