其他分享
首页 > 其他分享> > 移动零

移动零

作者:互联网

题目:

一.交换

void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void moveZeroes(int* nums,int numsSize) {
    if (numsSize == 1&&numsSize==0&&nums==null)
        return;

    for (int i = 0; i < numsSize; i++) {
        if (nums[i] == 0) {
            int temp = i + 1;
            int zero = i;
            while (temp < numsSize) {
                if (nums[temp] != 0){
                    swap(&nums[zero], &nums[temp]);
                    zero = temp;
                }
                temp++;
            }
        }
    }
}

二.填0

void moveZeroes(int* nums,int numsSize) {
    if (numsSize == 1&&numsSize==0&&nums==null)
        return;
    int temp=0;
    for(int i=0;i<numsSize;i++){
      if(nums[i]!=0){
        nums[temp]=nums[i];
        temp++;
    }
  }
    for(int i=temp;i<numsSize;i++)
        nums[i]=0;
}

三.一次循环

void moveZeroes(int* nums, int numsSize){
    if(nums==NULL) {
			return;
	}
	//两个指针i和j
	int j = 0;
	for(int i=0;i<numsSize;i++) {
		//当前元素!=0,就把其交换到左边,等于0的交换到右边
		if(nums[i]!=0) {
			int tmp = nums[i];
			nums[i] = nums[j];
			nums[j++] = tmp;
		}
	}
}

标签:numsSize,temp,nums,int,void,&&,移动
来源: https://www.cnblogs.com/cony1/p/16672177.html