zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    4.graph.h
    3.俄罗斯方块项目
    3.栈的实现
    26.多线程
    25.Detours劫持技术
    codeforces 616E Sum of Remainders (数论,找规律)
    poj2387 Til the Cows Come Home 最短路径dijkstra算法
    poj1274 The Perfect Stall (二分最大匹配)
    poj1459 Power Network (多源多汇最大流)
    Oracle RAC/Clusterware 多种心跳heartbeat机制介绍 RAC超时机制分析
  • 原文地址:https://www.cnblogs.com/llxblogs/p/7482165.html
Copyright © 2011-2022 走看看