题解 | #调整数组顺序使奇数位于偶数前面#

调整数组顺序使奇数位于偶数前面

http://www.nowcoder.com/practice/ef1f53ef31ca408cada5093c8780f44b

头尾双指针,一次遍历,头处理奇数,尾处理偶数;
时间复杂度:O(N)
空间复杂度:O(N)

public int[] reOrderArray (int[] array) {
        // write code here
        //双指针,头尾指针
        int[] nums = new int[array.length];
        int head = 0;
        int tail = array.length-1;
        int index_head = head;
        int index_tail = tail;
        while(head < array.length && tail >= 0){
            if(array[head] % 2 == 1){
                //奇数,放前面
                nums[index_head] = array[head];
                index_head++;
            }
            head++;
            if(array[tail] % 2 == 0){
                //从后到前,如果为偶数,则从后开始填
                nums[index_tail] = array[tail];
                index_tail--;
            }
            tail--;
        }
        return nums;
    }
全部评论

相关推荐

见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
评论
41
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务