zoukankan      html  css  js  c++  java
  • 【leetcode】调整数组顺序使奇数位于偶数前面

    //头尾指针
    int *exchange(int *nums, int numsSize, int *returnSize)
    {
        int left = 0;
        int right = numsSize - 1;
    
        while (left < right) {
            if ((nums[left] % 2) == 1) {
                left++;
                continue;
            }
            if ((nums[right] % 2) == 0) {
                right--;
                continue;
            }
            if ((nums[left] % 2) == 0 && (nums[right] % 2) == 1) {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
                right--;
            }
        }
        
        *returnSize = numsSize;
        return nums;
    }
    int* exchange(int* nums, int numsSize, int* returnSize){
        *returnSize = numsSize;
        if (numsSize <= 1)
            return nums;
        int odd_count = 0;
        int even_count = 0;
        int* odd_arr = (int*)malloc(sizeof(int)*numsSize);
        int* even_arr = (int*)malloc(sizeof(int)*numsSize);
        for (int i=0; i<numsSize; i++)
        {
            if (nums[i] % 2 == 1)
                odd_arr[odd_count++] = nums[i];        
            else
                even_arr[even_count++] = nums[i];
        }
        if (odd_count == 0 || even_count ==0)
            return nums;
        for (int j=odd_count; j<numsSize; j++)
        {
            odd_arr[j] = even_arr[j-odd_count];
        }
    
        return odd_arr;
    }
  • 相关阅读:
    python--输出spwm的数组
    爬虫二:爬取糗事百科段子
    爬虫一:爬取信息
    Python中的切片操作
    JSON
    python 中的异常处理与种类
    register的功能
    static的功能
    网络安全的认识
    VMware5.5-vCenter Converter(转换)
  • 原文地址:https://www.cnblogs.com/ganxiang/p/13524200.html
Copyright © 2011-2022 走看看