(lintcode)第31题,数组划分
来源:互联网 发布:苹果手机日志软件 编辑:程序博客网 时间:2024/06/13 10:34
给出一个整数数组 nums 和一个整数 k。划分数组(即移动数组 nums 中的元素),使得:
- 所有小于k的元素移到左边
- 所有大于等于k的元素移到右边
返回数组划分的位置,即数组中第一个位置 i,满足 nums[i] 大于等于 k。
注意事项
你应该真正的划分数组 nums,而不仅仅只是计算比 k 小的整数数,如果数组 nums 中的所有元素都比 k 小,则返回 nums.length。
样例
给出数组 nums = [3,2,2,1]
和 k = 2
,返回 1
.
思路:
左右各一个游标,不断向中间靠拢,左边的找到比k大或者相等的数为止,右边找到比k小的数为止,然后两者交换,直到两个游标相交。
public class Solution { /* * @param nums: The integer array you should partition * @param k: An integer * @return: The index after partition */ public int partitionArray(int[] nums, int k) { // write your code here if(nums.length==0) return 0; if(nums.length==1) return 1; int i,j; int flag=0; for(i=0,j=nums.length-1;i!=j&&i<nums.length&&j>=0;){ while(nums[i]<k&&i<nums.length-1){ i++; } while(nums[j]>=k&&j>0){ j--; } if(i>=j) break; int temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; flag=1; } if(i==0) return 0; if(flag==0) return i+1; return i; }}
阅读全文
0 0
- (lintcode)第31题,数组划分
- LintCode 31 数组划分
- LintCode-数组划分
- LintCode 数组划分
- LintCode:数组划分
- LintCode 数组划分
- lintcode之数组划分
- LintCode:数组划分
- 【LintCode】数组划分
- Lintcode 数组划分
- 数组划分--lintcode
- lintcode --数组划分
- LIntcode 数组划分
- LintCode-----31.数组划分
- 数组划分——LintCode
- (lintcode)第6题 合并排序数组
- LintCode 第41题 最大子数组
- <LeetCode> 题31:数组划分
- C++内联
- Spring Boot初识
- 【BZOJ1857】传送带(三分)
- 统计学---极端异常值的检测
- Blog的API(php裸写
- (lintcode)第31题,数组划分
- 实验(堆栈)
- [ZJOI2005]午餐 贪心+dp
- 深入理解Java虚拟机之对象存活算法的实现(2)
- 【Python数据分析与展示】(八)数据合并、规整化
- JavaScript(4)- DOM
- 消失的硬盘空间:du与df统计不一致的解决方法
- 责任链模式
- shell 脚本之变量嵌套