Lintcode: Partition Array, lintcodearray

Source: Internet
Author: User

Lintcode: Partition Array, lintcodearray

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 has the same practice, but there are two special cases: I did not consider

1. all elements in nums are greater than or equal to k, l pointer never shift, shoshould 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 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.