自学内容网 自学内容网

C语言刷题 LeetCode 30天挑战 (四)排序思想

//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:
//1. You must do this in-place without making a copy of the array
//2.Minimize the totalnumber of operations.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

void moveZeroes1(int *nums,int numsSize)
{
    while(true){
        int count = 0;
        for(int i=0; i+1<numsSize ;++i){
            if(nums[i] == 0 && nums[i+1] != 0){
                count++;
                nums[i] = nums[i+1];
                nums[i+1] = 0;
                break;
            }
        }
        if(count <= 0){
            break;
        }
    }
    for(int k=0; k<numsSize ;++k)
        printf("%d ",nums[k]);
}

void moveZeroes2(int *nums,int numsSize)
{
    int count=0;
    for(int i=0; i<numsSize ;++i){
        if(nums[i]!=0){
            nums[count++] = nums[i];
        }
    }
    for(int j=count; j<numsSize ;++j)
        nums[j] = 0;

    for(int k=0; k<numsSize ;++k)
        printf("%d ",nums[k]);
}
 
int main()
{
    int nums[] = {12,0,0,0,1,0,3,12};
    moveZeroes1(nums,sizeof(nums)/sizeof(nums[0]));
    moveZeroes2(nums,sizeof(nums)/sizeof(nums[0]));
    return 0;
}


原文地址:https://blog.csdn.net/weixin_64593595/article/details/142601438

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!