LeetCode 283. Move Zeroes

题目描述

  • 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.

Example:

Input:  [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

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

题目解读

  • 输入一个数字数组,将这个数组中的0放到最后面,然后不为0的数字按照与按顺序输出

解题思路

  • 依次循环,碰到为0的数字就去和后面的不为0数字置换

Code

# include<stdio.h>

void moveZeroes(int* nums, int numsSize) 
{
    int i, j;
    int temp;

    for(i = 0; i < numsSize - 1; i ++)
    {
        if(nums[i] == 0)
        {
            for(j = i + 1; j < numsSize; j ++)
            {
                if(nums[j] != 0)
                {
                    temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                    break;
                }
            }
        }
    }

    for(i = 0; i < numsSize; i ++)
    {
        printf("%d ", nums[i]);
    }
}


int main()
{   
    int a[10] = {0, 1, 0, 3, 12};
    int numsSize = 5;
    moveZeroes(a, numsSize);
}

思考

  • 结果差强人意...
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • Move Zeroes 描述:Given an array nums, write a function to m...
    cherrycoca阅读 277评论 0 0
  • Question 把数组所有的值为0的元素移到末尾 Given an array nums, write a fu...
    Sinexs阅读 1,057评论 0 1
  • 生活中我们总爱处处和别人比较,比较谁赚的多,比较谁房子大,比较谁升迁的快,比较谁的子女有出息……比着比着就心...
    欣然的世界阅读 207评论 0 0
  • 《岛上书店》中,A.J.和阿米莉娅结婚的时候,阿米莉娅邀请了她的“大学同学”读了《迟暮花开》中的一段:因为从心底害...
    地上不再有草阅读 181评论 0 1