Partition Array

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 right

Return the partitioning index, i.e the first index i nums[i] >= k.

public int partitionArray(int[] nums, int k) {
        //write your code here
          if(nums == null || nums.length == 0){
        return 0;
    }

    int left = 0, right = nums.length - 1;
    while (left <= right) {
        while (left <= right && nums[left] < k) {
            left++;
        }
        while (left <= right && nums[right] >= k) {
            right--;
        }

        // corner: if all nums smaller than k, return nums.length
        if (left < right) {
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;

            left++;
            right--;
        }
    }
    return left;
}

Sort Letters

Given a string which contains only letters. Sort it by lower case first and upper case second.

  1. In ASCII, lower case number is bigger

public void sortLetters(char[] chars) {
    int left = 0, right = chars.length -1;
    while(left <= right){
        while(left <= right && chars[left] >= 'a'){
            left++;
        }
        while(left <= right && chars[right] <= 'Z'){
            right--;
        }

        if(left < right){
            char tmp = chars[left];
            chars[left] = chars[right];
            chars[right] = tmp;
        }
        left++;
        right--;
    }
}

Last updated