lintcode数组划分
2018-03-12 23:40
197 查看
题目:
给出一个整数数组 nums 和一个整数 k。划分数组(即移动数组 nums 中的元素),使得:所有小于k的元素移到左边
所有大于等于k的元素移到右边
返回数组划分的位置,即数组中第一个位置 i,满足 nums[i] 大于等于 k。
样例:
给出数组 nums =[3,2,2,1]和 k =
2,返回
1
思路:
从数组两头分别找大于k和小于k的数,并进行交换答案:
private void swap(int[] nums, int x, int y){ int tmp = nums[x]; nums[x] = nums[y]; nums[y] = tmp; } public int partitionArray(int[] nums, int k) { //write your code here if(nums == null || nums.length == 0) return 0; int start = 0, end = nums.length - 1; while(true){ while(start < end && nums[start] < k) start++; while(start < end && nums[end] >= k) end--; if(start >= end) break; swap(nums, start, end); } return nums[end] < k ? end + 1 : end; }
相关文章推荐
- LintCode:数组划分
- 数组划分——LintCode
- lintcode-31-数组划分
- lintcode-31数组划分
- lintcode 数组划分问题
- LintCode-数组划分
- LintCode-数组划分
- (lintcode)第31题,数组划分
- LIntcode 数组划分
- LintCode-数组划分
- LintCode 数组划分
- 数组划分--lintcode
- LintCode:数组划分
- 【LintCode】数组划分
- lintcode --数组划分
- 2013年8月13日、 重载|数组|内存的划分|栈内存、堆内存
- [Lintcode]Maximum Subarray III最大子数组 III
- bestcoder——数组划分
- Leetcode 410. Split Array Largest Sum 划分数组 解题报告
- lintcode ----奇偶分割数组