Given an array nums
of integers and an int k
, partition the array (i.e move the elements in "nums") such that:數組
Return the partitioning index, i.e the first index i nums[i] >= k.markdown
這圖片是真滴大。。。app
這道題目,換個方式,便是說,比k小的有多少個數,有兩種方法:spa
1)升序排序,而後遍歷,遇到第一個 >=k 的數便可返回,代碼以下:code
public class Solution { /** * @param nums: The integer array you should partition * @param k: An integer * @return: The index after partition */ public int partitionArray(int[] nums, int k) { // write your code here int length = nums.length; if(length == 0){ return 0; } sort(nums); for(int i = 0; i < length; i++){ if(nums[i] >= k){ return i; } } return length; } public static void sort(int[] nums){ int length = nums.length; for(int i = 0; i < length; i++){ for(int j = i+1; j < length; j++){ if(nums[i] > nums[j]){ int temp = nums[j]; nums[j] = nums[i]; nums[i] = temp; } } } } }
這道題的要求其實比較低,試着手寫了一個冒泡排序代進去,仍是能夠經過的;blog
2)遍歷數組,統計比k小的數count,那麼可能出現的狀況有:排序
a)count == 0,即數組中全部元素都>=k,按照題目要求,此時應該返回0;圖片
b)count > 0 && count < length,那麼說明數組中有count個數比k要小:返回k;ip
c)count == length,即全部元素都比k要小,按照題目要求,此時應該返回length;element
綜上:
public class Solution { /** * @param nums: The integer array you should partition * @param k: An integer * @return: The index after partition */ public int partitionArray(int[] nums, int k) { // write your code here int length = nums.length; if(length == 0){ return 0; } int count = 0; for(int i = 0; i < length; i++){ if(nums[i] < k){ count++; } } if(count > 0){ if(count == length){ return length; }else{ return count; } } return 0; } }
不知道是否有其餘思路(至少目前的我想不到哈哈哈)