国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Lintcode: Partition Array

2019-11-14 23:35:07
字體:
來源:轉載
供稿:網友
Lintcode: Partition Array
Given an array "nums" of integers and an int "k", Partition the array (i.e move the elements in "nums") such that,    * All elements < k are moved to the left    * All elements >= k are moved to the rightReturn the partitioning Index, i.e the first index "i" nums[i] >= k.NoteYou should do really partition in array "nums" instead of just counting the numbers of integers smaller than k.If all elements in "nums" are smaller than k, then return "nums.length"ExampleIf nums=[3,2,2,1] and k=2, a valid answer is 1.ChallengeCan you partition the array in-place and in O(n)?

Quick Sort 一樣的做法,只是有兩種情況特殊處理:我第一次做的時候沒有考慮到

1. all elements in nums are greater than or equal to k, l pointer never shift, should return r

2.all elements in nums are smaller than k, r pointer never shift, shoud return r+1

 1 public class Solution { 2     /**  3      *@param nums: The integer array you should partition 4      *@param k: As description 5      *return: The index after partition 6      */ 7     public int partitionArray(ArrayList<Integer> nums, int k) { 8         //write your code here 9         if (nums==null || nums.size()==0) return 0;10         int l=0, r=nums.size()-1;11         while (true) {12             while (l<r && nums.get(r)>=k) {13                 r--;14             }15             while (l<r && nums.get(l)<k) {16                 l++;17             }18             if (l == r) break;19             swap(l, r, nums);20         }21         if (l==0 && nums.get(l)>=k) return r;22         if (r==nums.size()-1 && nums.get(l)<k) return r+1;23         return r+1;24     }25     26     public void swap(int l, int r, ArrayList<Integer> nums) {27         int temp = nums.get(l);28         nums.set(l, nums.get(r).intValue());29         nums.set(r, temp);30     }31 }


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 顺义区| 惠来县| 洛川县| 册亨县| 县级市| 和龙市| 永春县| 玛曲县| 大渡口区| 河南省| 南汇区| 恩施市| 万山特区| 通道| 工布江达县| 井冈山市| 凌源市| 海安县| 疏勒县| 怀集县| 芦溪县| 潮州市| 宾川县| 伊金霍洛旗| 静海县| 兴文县| 海城市| 凤冈县| 新龙县| 华容县| 开平市| 三都| 琼中| 金堂县| 孟州市| 新河县| 华阴市| 商河县| 邵武市| 遂溪县| 鲁山县|