21544661
Posted 保护眼睛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了21544661相关的知识,希望对你有一定的参考价值。
剑指offer
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
public class Solution21 {
public static void main(String[] args) {
System.out.println(Arrays.toString(exchange(new int[]{1, 2, 3, 4})));
}
public static int[] exchange(int[] nums) {
int i = 0;
int j = nums.length - 1;
while (i < j) {
while (i < j && nums[i] % 2 != 0) {
i++;
}
while (i < j && nums[j] % 2 == 0) {
j--;
}
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
return nums;
}
}
剑指 Offer 54. 二叉搜索树的第k大节点
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
class Solution54 {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
public int kthLargest(TreeNode root, int k) {
preOrderTree(root);
for (int i = 0; i < k - 1; i++) {
priorityQueue.poll();
}
return priorityQueue.peek();
}
public void preOrderTree(TreeNode root) {
if (root == null)
return;
priorityQueue.offer(root.val);
preOrderTree(root.left);
preOrderTree(root.right);
}
}
class Solution54_2 {
int k;
int res;
public int kthLargest(TreeNode root, int k) {
this.k = k;
dfs(root);
return res;
}
public void dfs(TreeNode root) {
if (root == null || k == 0)
return;
dfs(root.right);
if (--k == 0)
res = root.val;
dfs(root.left);
}
}
剑指 Offer 46. 把数字翻译成字符串
class Solution46 {
public static int translateNum(int num) {
if (num < 10) {
return 1;
}
int tmp = num % 100;
if (tmp < 10 || tmp >= 26) {
return translateNum(num / 10);
} else {
return translateNum(num / 10) + translateNum(num / 100);
}
}
public static void main(String[] args) {
System.out.println(translateNum(12258));
}
}
剑指 Offer 61. 扑克牌中的顺子
class Solution61 {
public static void main(String[] args) {
System.out.println(isStraight(new int[]{0, 0, 8, 5, 4}));
}
public static boolean isStraight(int[] nums) {
Arrays.sort(nums);
int count = 0;
int sub = 0;
for (int i = 0; i < 4; i++) {
if (nums[i] == 0) {
count++;
continue;
}
if (nums[i + 1] == nums[i]) return false;
sub += (nums[i + 1] - nums[i] - 1);
}
return sub <= count;
}
}
以上是关于21544661的主要内容,如果未能解决你的问题,请参考以下文章