274. H-Index
这道题用一个新的数组,存储每个每个引用次数出现的频率,注意如果某文章引用次数大于科学家发文章的总数,则看作等于发文章总数的频率。
然后再从前往后加计算满足H-INDEX条件的最大值。
public class Solution {
public int hIndex(int[] citations) {
int len = citations.length;
if (len <=0) {
return 0;
}
int[] arr= new int[len + 1];
for (int i = 0; i < len; i++) {
if (citations[i] >= len) {
arr[len]++;
}
else {
arr[citations[i]]++;
}
}
int k = 0;
int res = 0;
for (int i = len; i >= 0; i--) {
k += arr[i];
if (k >= i) {
return i;
}
}
return 0;
}
}
324. Wiggle Sort II
先找出数组中中位数,然后小于这个数的放奇数,其他放偶数。找中位数用到快排思想。
public class Solution {
public void wiggleSort(int[] nums) {
int median = findKthLargest(nums, (nums.length + 1) / 2);
int n = nums.length;
int left = 0, i = 0, right = n - 1;
while (i <= right) {
if (nums[newIndex(i,n)] > median) {
swap(nums, newIndex(left++,n), newIndex(i++,n));
}
else if (nums[newIndex(i,n)] < median) {
swap(nums, newIndex(right--,n), newIndex(i,n));
}
else {
i++;
}
}
}
private int newIndex(int index, int n) {
return (1 + 2 * index) % (n | 1);
}
private int findKthLargest(int[] nums, int k) {
return findKthLargest(nums, k, 0, nums.length - 1);
}
private int findKthLargest(int[] nums, int k, int l, int r) {
if (l >= r) {
return nums[l];
}
int m = partition(nums, l, r);
if (m == k) {
return nums[m];
}
else if (m < k) {
return findKthLargest(nums, k, m + 1, r);
}
else {
return findKthLargest(nums, k, l, m - 1);
}
}
private int partition(int[] nums, int l, int r) {
int pivot = nums[l];
int m = l;
int n = l+1;
while(n <= r) {
if(nums[n] < pivot){
swap(nums, ++m, n);
}
n++;
}
swap(nums, l, m);
return m;
}
public void swap(int[] nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}