面试题45. 把数组排成最小的数
思路
使用到了快速排序
class Solution {
public String minNumber(int[] nums) {
// 初始化字符串数组
String[] strs = new String[nums.length];
// 循环添加
for(int i = 0; i < nums.length; i++){
strs[i] = String.valueOf(nums[i]);
}
// 快速排序
quickSort(strs, 0, strs.length - 1);
StringBuilder res = new StringBuilder();
for(String s : strs)
res.append(s);
return res.toString();
}
void quickSort(String[] strs, int l, int r){
if(l >= r) return;
int i = l, j = r;
String tmp = strs[i];
while(i < j){
while((strs[j] + strs[l]).compareTo(strs[l] + strs[j]) >= 0 && i < j) j--;
while((strs[i] + strs[l]).compareTo(strs[l] + strs[i]) <= 0 && i < j) i++;
tmp = strs[i];
strs[i] = strs[j];
strs[j] = tmp;
}
strs[i] = strs[l];
strs[l] = tmp;
quickSort(strs, l, i - 1);
quickSort(strs, i + 1, r);
}
}
面试题61. 扑克牌中的顺子
思路
class Solution {
public boolean isStraight(int[] nums) {
Set<Integer> mySet = new HashSet<>();
int max = 0, min = 14;
for(int num : nums){
if(num == 0) continue;
if(mySet.contains(num)) return false;
mySet.add(num);
max = Math.max(max, num);
min = Math.min(min, num);
}
return max - min < 5;
}
}
40. 最小的k个数
思路
快速排序
class Solution {
public int[] getLeastNumbers(int[] arr, int k) {
quickSort(arr, 0, arr.length - 1);
return Arrays.copyOf(arr, k);
}
void quickSort(int[] arr, int l, int r){
if(l >= r) return;
int i = l, j = r;
while(i < j){
while(i < j && arr[j] >= arr[l]) j--;
while(i < j && arr[i] <= arr[l]) i++;
swap(arr, i, j);
}
swap(arr, i, l);
quickSort(arr, l, i - 1);
quickSort(arr, i + 1, r);
}
private void swap(int[] arr, int i, int j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
41. 数据流中的中位数
思路
大顶堆和小顶堆,学到了
class MedianFinder {
Queue<Integer> A, B;
/** initialize your data structure here. */
public MedianFinder() {
A = new PriorityQueue<>(); // 小
B = new PriorityQueue<>((x, y) -> (y - x)); // 大
}
public void addNum(int num) {
if(A.size() != B.size()){
A.add(num);
B.add(A.poll());
}else{
B.add(num);
A.add(B.poll());
}
}
public double findMedian() {
return A.size() != B.size() ? A.peek() : (A.peek() + B.peek()) / 2.0;
}
}
标签:arr,return,String,17,16,int,strs,num,排序
From: https://www.cnblogs.com/vincy9501/p/17029088.html