1. 程式人生 > 其它 >演算法常考題目

演算法常考題目

演算法常考題目
25K個一組翻轉連結串列
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (k == 1 || head.next == null) return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode end = dummy;
while (end.next != null) {
for (int i = 0; i < k && end != null; i++) end = end.next;
if (end == null) break;
ListNode start = pre.next;
ListNode next = end.next;
end.next = null;
pre.next = reverse(start);

start.next = next;
pre = start;
end = pre;
}
return dummy.next;
}

private ListNode reverse(ListNode head) {
ListNode pre = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
}

121買賣股票的最佳時機
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) minPrice = prices[i];
int tmp = prices[i] - minPrice;
if (tmp > maxProfit) maxProfit = tmp;
}
return maxProfit;
}
}

15三數之和
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
int left = i + 1, right = nums.length-1, sum = 0 - nums[i];
while (left < right) {
if (nums[left] + nums[right] == sum) {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left+1]) left++;
while (left < right && nums[right] == nums[right-1]) right--;
left++;
right--;
} else if (nums[left] + nums[right] < sum) left++;
else right--;
}
}
return res;
}
}

155最小棧
class MinStack {

int min = Integer.MAX_VALUE;
Stack<Integer> stack = null;

public MinStack() {
stack = new Stack<>();
}

public void push(int val) {
if (val <= min) {
stack.push(min);
min = val;
}
stack.push(val);
}

public void pop() {
if (stack.pop() == min) min = stack.pop();
}

public int top() {
return stack.peek();
}

public int getMin() {
return min;
}
}

124二叉樹中的最大路徑和
class Solution {
private int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
searchTree(root);
return max;
}

private int searchTree(TreeNode root) {
if (root == null) return 0;
int leftNum = Math.max(0, searchTree(root.left));
int rightNum = Math.max(0, searchTree(root.right));
max = Math.max(leftNum+rightNum+root.val, max);
return Math.max(leftNum,rightNum) + root.val;
}
}

199二叉樹的右檢視
class Solution {
private List<Integer> res = new ArrayList<>();
public List<Integer> rightSideView(TreeNode root) {
searchTree(root,0);
return res;
}

private void searchTree(TreeNode root, int deep) {
if (root == null) return;
if (deep == res.size()) res.add(root.val);
deep++;
searchTree(root.right,deep);
searchTree(root.left,deep);
}
}

3無重複字元的最長子串
class Solution {
public int lengthOfLongestSubstring(String s) {
char[] chars = s.toCharArray();
int start = 0, end = 0, max = 0;
int[] tmp = new int[128];
Arrays.fill(tmp, -1);
while (end < chars.length) {
if (tmp[chars[end]] >= start) {
max = Math.max(max, end-start);
start = tmp[chars[end]]+1;
}
tmp[chars[end]] = end;
end++;
}
return Math.max(max, end-start);
}
}

236二叉樹的最近公共祖先
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if (left == null) return right;
if (right == null) return left;
return root;
}
}

322零錢兌換
class Solution {
public int coinChange(int[] coins, int amount) {
int max = amount + 1;
int[] dp = new int[amount + 1];
Arrays.fill(dp, max);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int j = 0; j < coins.length; j++) {
if (coins[j] <= i) {
dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
}

215陣列中的第K個最大元素
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> queue = new PriorityQueue<>(k);
for (int i = 0; i < nums.length; i++) {
queue.offer(nums[i]);
if (queue.size() > k) {
queue.poll();
}
}
return queue.peek();
}
}

226翻轉二叉樹
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
}


122買賣股票的最佳時機II
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
for (int i = 1; i < prices.length; i++) {
int money = prices[i] - prices[i-1];
if (money > 0) {
result += money;
}
}
return result;
}
}

153尋找旋轉排序陣列中的最小值
class Solution {
public int findMin(int[] nums) {
int low = 0;
int high = nums.length - 1;
while (low < high) {
int pivot = low + (high - low) / 2;
if (nums[pivot] < nums[high]) {
high = pivot;
} else {
low = pivot + 1;
}
}
return nums[low];
}
}

55跳躍遊戲
class Solution {
public boolean canJump(int[] nums) {
int len = nums.length;
if (len == 1) return true;
for (int i = len-2; i >= 0; i--) {
if (i + nums[i] >= len-1) len = i+1;
}
return len == 1;
}
}

5最長迴文子串
class Solution {
public String longestPalindrome(String s) {
int len = s.length();
if (len < 2) {
return s;
}
int max = 0;
int start = 0;
char[] chars = s.toCharArray();
boolean[][] dp = new boolean[len][len];
for (int i = 0; i < len; i++) {
for (int j = 0; j+i < len; j++) {
if (i == 0) dp[j][j+i] = true;
else if (i == 1) dp[j][j+i] = chars[j] == chars[j+i];
else dp[j][j+i] = dp[j+1][j+i-1] && chars[j] == chars[j+i];
if (dp[j][j+i] && i+1 > max) {
max = i+1;
start = j;
}
}
}
return s.substring(start,start+max);
}
}

劍指03陣列中重複的數字
class Solution {
public int findRepeatNumber(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
int num = nums[i];
if (num < 0) num += n;
if (nums[num] < 0) return num;
nums[num] -= n;
}
return -1;
}
}

劍指55平衡二叉樹
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null)
return true;
//分別計算左子樹和右子樹的高度
int left = depth(root.left);
int right = depth(root.right);
//這兩個子樹的高度不能超過1,並且他的兩個子樹也必須是平衡二叉樹
return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}

//計算樹中節點的高度
public int depth(TreeNode root) {
if (root == null)
return 0;
return Math.max(depth(root.left), depth(root.right)) + 1;
}
}


----------------------------------------------------------------------
程式碼題目
1.兩個執行緒交替列印1-10
public class TestPrintNumber {
public static void main(String[] args) {
Number number = new Number();
new Thread(number, "A").start();
new Thread(number, "B").start();
}

static class Number implements Runnable {
private int i = 0;
@Override
public void run() {
while (true) {
synchronized (this) {
notify();
if (i < 10) {
i++;
System.out.println(Thread.currentThread().getName() + ": " + i);
} else {
break;
}
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
2.AVL樹中各種旋轉
public class Solution{
// LL情況下的旋轉
private TreeNode leftleft(TreeNode root) {
TreeNode newRoot = root.left;
root.left = newRoot.right;
newRoot.right = root;
return newRoot;
}
//RR情況下的旋轉
private TreeNode rightright(TreeNode root) {
TreeNode newRoot = root.right;
root.right = newRoot.left;
newRoot.left = root;
return newRoot;
}
// LR下情況
private TreeNode leftRight(TreeNode root) {
root.left = rightright(root.left);
return leftleft(root);
}
// RL情況
private TreeNode rightleft(TreeNode root) {
root.right = leftleft(root.right);
return rightright(root);
}
}