博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
遍历数组排序,负数在左,正数在右
阅读量:4604 次
发布时间:2019-06-09

本文共 1182 字,大约阅读时间需要 3 分钟。

原文:


问题描述:

有一个整形数组,包含正数和负数,然后要求把数组内的所有负数移至正数的左边,且保证相对位置不变,要求时间复杂度为O(n), 空间复杂度为O(1)。例如,{10, -2, 5, 8, -4, 2, -3, 7, 12, -88, -23, 35}变化后是{-2, -4,-3, -88, -23,5, 8 ,10, 2, 7, 12, 35}。

解决方法

原文:

实现原理是:两个变量记录左右节点,两边分别开始遍历。左边的节点遇到负值继续前进,遇到正值停止。右边的节点正好相反。然后将左右节点的只进行交换,然后再开始遍历直至左右节点相遇。

这种方式的时间复杂度是O(n).空间复杂度为O(1)

以下为java的实现:

原文:

public void setParted1(int[] a, int left, int right) {        if (left >= right || left == a.length || right == 0) {            for (int i = 0; i < a.length; i++) {                System.out.println(a[i]);            }            return;        }        while (a[left] < 0) {            left++;        }        while (a[right] >= 0) {            right--;        }        if (left >= right || left == a.length || right == 0) {            for (int i = 0; i < a.length; i++) {                System.out.println(a[i]);            }            return;        }        swap(a, left, right);        left++;        right--;        setParted1(a, left, right);    }    private void swap(int a[], int left, int right) {        int temp = 0;        temp = a[left];        a[left] = a[right];        a[right] = temp;    }

原文:

转载于:https://www.cnblogs.com/66it/p/10486010.html

你可能感兴趣的文章
python-haproxy作业讲解视频总结
查看>>
mui搜索框 搜索点击事件
查看>>
A == B ?
查看>>
洛谷P3763 [Tjoi2017]DNA 【后缀数组】
查看>>
UVa 442 Matrix Chain Multiplication(矩阵链,模拟栈)
查看>>
多种方法求解八数码问题
查看>>
spring mvc ModelAndView向前台传值
查看>>
(黑客游戏)HackTheGame1.21 过关攻略
查看>>
Transparency Tutorial with C# - Part 2
查看>>
android 文件上传
查看>>
ASCII 码表对照
查看>>
javascript的DOM操作获取元素
查看>>
Shuffle'm Up(串)
查看>>
20145219 《Java程序设计》第06周学习总结
查看>>
C# 执行bat文件并取得回显
查看>>
基于YOLO的Autonomous driving application__by 何子辰
查看>>
javascript中的继承
查看>>
iOS-如何写好一个UITableView
查看>>
如何在Objective-C中实现链式语法
查看>>
select2 下拉搜索控件
查看>>