File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ ## 一、题目
2+
3+ > Given an array nums of integers and an int k, partition the array (i.e move the elements in "nums") such that:
4+ >
5+ > - All elements < k are moved to the left
6+ > - All elements >= k are moved to the right
7+ > - Return the partitioning index, i.e the first index i nums[ i] >= k.
8+ >
9+ > * Notice*
10+ >
11+ > You should do really partition in array nums instead of just counting the numbers of integers smaller than k.
12+ >
13+ > If all elements in nums are smaller than k, then return nums.length
14+
15+ ## 二、解题思路
16+
17+ 根据给定的k,也就是类似于Quick Sort中的pivot,将array从两头进行缩进,时间复杂度 O(n)
18+
19+ ## 三、解题代码
20+
21+ ``` java
22+ public class Solution {
23+ private void swap (int i , int j , int [] arr ) {
24+ int tmp = arr[i];
25+ arr[i] = arr[j];
26+ arr[j] = tmp;
27+ }
28+ /**
29+ *@param nums: The integer array you should partition
30+ *@param k: As description
31+ *return: The index after partition
32+ */
33+ public int partitionArray (int [] nums , int k ) {
34+
35+ int pl = 0 ;
36+ int pr = nums. length - 1 ;
37+ while (pl <= pr) {
38+ while (pl <= pr && nums[pl] < k) {
39+ pl++ ;
40+ }
41+ while (pl <= pr && nums[pr] >= k) {
42+ pr-- ;
43+ }
44+ if (pl <= pr) {
45+ swap(pl, pr, nums);
46+ pl++ ;
47+ pr-- ;
48+ }
49+ }
50+ return pl;
51+ }
52+ }
53+ ```
54+
You can’t perform that action at this time.
0 commit comments