LeetCode&&剑指offer


2021-08-03 21:15:22 星期二

509. 斐波那契数

https://leetcode-cn.com/problems/fibonacci-number/submissions/

class Solution {
    public int fib(int n) {
        if(n < 2){
            return n;
        }
        int f = 0, s = 1;
        for(int i = 2; i <= n; i++){
            int t = f + s;
            f = s;
            s = t;
        }
        return s;
    }
}

image

JZ50 数组中重复的数字

https://www.nowcoder.com/practice/6fe361ede7e54db1b84adc81d09d8524?tpId=13&tqId=11203&tab=answerKey&from=cyc_github
大佬总结:
https://github.com/CyC2018/CS-Notes/blob/master/notes/3. 数组中重复的数字.md

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param numbers int整型一维数组 
     * @return int整型
     */
	 
	 //方法一
    public int duplicate (int[] numbers) {
        int[] tmp = new int[numbers.length];
        for(int i = 0; i < numbers.length; i++){
            if(tmp[numbers[i]] > 0){
                return numbers[i];
            }
            tmp[numbers[i]]++;
        }
        return -1;
    }
	
	//方法二
 public int duplicate (int[] numbers) {
        for(int i = 0; i < numbers.length; i++){
            while(i != numbers[i]){
                if(numbers[i] == numbers[numbers[i]]){
                    return numbers[i];
                }
                int t = numbers[i];
                numbers[i] = numbers[numbers[i]];
                numbers[t] = t;
            }
        }
         return -1;
     }
}

2021-08-04 21:32:21 星期三

167. 两数之和 II - 输入有序数组

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int i = 0, j = numbers.length - 1;
        while (i < j){
            if (numbers[i] + numbers[j] == target) return new int[] {i + 1, j + 1};
            if (numbers[i] + numbers[j] > target){
                j--;
                continue;
            }else {
                i++;
                continue;
            }
        }
        return null;
    }
}

image

633. 平方数之和

class Solution {
    public boolean judgeSquareSum(int c) {
        int sqrt = (int) Math.sqrt(c);
        int i = 0, j = sqrt;
        while (i <= j) {
            if (i*i + j*j == c) return true;
            if (i*i + j*j > c){
                j--;
            }else {
                i++;
            }
        }
        return false;
    }
}

image

345. 反转字符串中的元音字母

class Solution {
    public String reverseVowels(String s) {
        List<Character> t = Arrays.asList('a', 'o', 'e', 'i', 'u', 'A', 'O', 'E', 'I' ,'U');
        char[] array = s.toCharArray();
        int i = 0, j = array.length - 1;
        while (i <= j){
            if (t.contains(array[i]) && t.contains(array[j])){
                char tmp = array[i];
                array[i] = array[j];
                array[j] = tmp;
                i++;
                j--;
            }else if (t.contains(array[i])){
                j--;
            }else if (t.contains(array[j])){
                i++;
            }else {
                i++;
                j--;
            }
        }
        return new String(array);
    }
}

image

2021-08-05 23:14:32 星期四

680. 验证回文字符串 Ⅱ

class Solution {
    public boolean validPalindrome(String s) {
        if (s == null) return false;
        if (s.length() < 2) return true;
        char[] array = s.toCharArray();
        int i = 0, j = array.length - 1;
        while (i < j) {
            if (array[i] == array[j]) {
                i++;
                j--;
                continue;
            } else {
                return isPalindrome(new String(array, i, j - i)) || isPalindrome(new String(array, i + 1, j - i));
            }
        }
        return true;
    }

    public boolean isPalindrome(String s) {
        int i = 0, j = s.length() - 1;
        while (i < j) {
            if (s.charAt(i) != s.charAt(j)) return false;
            i++;
            j--;
        }
        return true;
    }
}

image

88. 合并两个有序数组

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int i = m - 1, j = n - 1, k = m + n - 1;
        while (i >= 0 && j >= 0){
            if (nums1[i] >= nums2[j]){
                nums1[k--] = nums1[i--];
            }else {
                nums1[k--] = nums2[j--];
            }
        }
        if (i >= 0){
            while (k >= 0){
                nums1[k--] = nums1[i--];
            }
        }else {
            while (k >= 0){
                nums1[k--] = nums2[j--];
            }
        }
    }
}

image

141. 环形链表

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) return false;
        ListNode h1 = head, h2 = head.next;
        while (h1 != null && h2 != null && h2.next != null){
            if (h1 == h2) return true;
            h1 = h1.next;
            h2 = h2.next.next;
        }
        return false;
    }
}

image

2021-08-07 22:49:23 星期六

524. 通过删除字母匹配到字典里最长单词

class Solution {
    public String findLongestWord(String s, List<String> dictionary) {
        if(dictionary == null) return "";
        Collections.sort(dictionary);
        int i = 0, max = 0;
        String result = "";
        while (i < dictionary.size()){
            if (isSubStr(s, dictionary.get(i)) && dictionary.get(i).length() > max){
                max = dictionary.get(i).length();
                result = dictionary.get(i);
            }
            i++;
        }
        return result;
    }
    private boolean isSubStr(String s, String target){
        int i = 0, j = 0;
        while (i < s.length() && j < target.length()){
            if (s.charAt(i) == target.charAt(j)){
                j++;
            }
            i++;
        }
        return j == target.length();
    }
}

image

215. 数组中的第K个最大元素

class Solution {
    public int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);
        return nums[nums.length - k];
    }
}

image

2021-08-08 10:57:32 星期日

20. 有效的括号

class Solution {
    public boolean isValid(String s) {
        char[] array = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (char c : array) {
            if (c == '(' || c == '[' || c == '{'){
                stack.push(c);
            }else {
                if (stack.isEmpty()) return false;
                switch (stack.pop()){
                    case '(':
                        if (c != ')') {
                            return false;
                        }
                        break;
                    case '[':
                        if (c != ']'){
                            return false;
                        }
                        break;
                    case '{':
                        if (c != '}'){
                            return false;
                        }
                        break;
                }
            }
        }
        return stack.isEmpty();
    }
}

image

2021-08-09 21:10:23 星期一

232. 用栈实现队列

class MyQueue {

    Stack<Integer> inStack = new Stack<>();
    Stack<Integer> outStack = new Stack<>();
    /** Initialize your data structure here. */
    public MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        inStack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (!outStack.isEmpty()) {
            return outStack.pop();
        }
        while (!inStack.isEmpty()) {
            outStack.push(inStack.pop());
        }
        return outStack.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if (!outStack.isEmpty()) {
            return outStack.peek();
        }
        while (!inStack.isEmpty()) {
            outStack.push(inStack.pop());
        }
        return outStack.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return outStack.isEmpty() && inStack.isEmpty();
    }
}

image

69. x 的平方根

class Solution {
    public int mySqrt(int x) {
        if (x < 2) return x;
        int left = 1, right = x;
        while (left <= right){
            int med = (left + right)/ 2;
            int sqrt = x / med;
            if (sqrt == med){
                return med;
            }else if (sqrt > med){
                left = med + 1;
            }else {
                right = med - 1;
            }
        }
        return right;
    }
}

image

2021-09-17 23:54:14 星期五

455. 分发饼干

https://leetcode-cn.com/problems/assign-cookies/

import java.util.Arrays;
class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int x = 0, y = 0;
        while (x < g.length && y < s.length){
            if (g[x] <= s[y]){
                x++;
                y++;
            }else{
                y++;
            }
        }
        return x;
    }
}

image

70. 爬楼梯

https://leetcode-cn.com/problems/climbing-stairs/

class Solution {
    public int climbStairs(int n) {
        if (n <= 2) return n;
        int s1 = 1, s2 = 2;
        for (int i = 3; i <= n; i++){
            s2 += s1;
            s1 = s2 - s1;
        }
        return s2;
    }
}

image

120. 三角形最小路径和

https://leetcode-cn.com/problems/triangle/

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        if (triangle.size() == 1) {
            return triangle.get(0).get(0);
        }
        for (int i = 1; i < triangle.size(); i++) {
            for (int j = 0; j <= i; j++) {
                if (j == 0) {
                    triangle.get(i).set(j, triangle.get(i).get(j) + triangle.get(i - 1).get(0));
                } else if (j == i) {
                    triangle.get(i).set(j, triangle.get(i).get(j) + triangle.get(i - 1).get(j - 1));
                } else {
                    triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i - 1).get(j - 1), triangle.get(i - 1).get(j)));

                }
            }
        }
        int min = triangle.get(triangle.size() - 1).get(0);
        for (int i = 1; i < triangle.get(triangle.size() - 1).size(); i++) {
            min = Math.min(min, triangle.get(triangle.size() - 1).get(i));
        }
        return min;
    }
}

image

64. 最小路径和

https://leetcode-cn.com/problems/minimum-path-sum/

class Solution {
    public int minPathSum(int[][] grid) {
        for (int i = 1; i < grid.length; i++){
            grid[i][0] += grid[i - 1][0];
        }
        for (int i = 1; i < grid[0].length; i++){
            grid[0][i] += grid[0][i - 1];
        }
        for (int i = 1; i < grid.length; i++){
            for (int j = 1; j < grid[i].length; j++){
                grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
            }
        }
        return grid[grid.length - 1][grid[grid.length - 1].length - 1];
    }
}

image

2021-09-28 13:03:10 星期二

53. 最大子序和

https://leetcode-cn.com/problems/maximum-subarray/

class Solution {
    public int maxSubArray(int[] nums) {
        int max = nums[0];
        for (int i = 1; i < nums.length; i++) {
            nums[i] = Math.max(nums[i], nums[i - 1] + nums[i]);
            max = Math.max(max, nums[i]);
        }
        return max;
    }
}

image

2021-10-05 16:22:46 星期二

剑指 Offer II 024. 反转链表

https://leetcode-cn.com/problems/UHnkqh/

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode next = null, prev = null;
        while (head != null){
            next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }
}

image

2021-10-06 16:08:45 星期三

414. 第三大的数

https://leetcode-cn.com/problems/third-maximum-number/

class Solution {
    public int thirdMax(int[] nums) {
        nums = Arrays.stream(nums).distinct().toArray();
        Arrays.sort(nums);
        if (nums.length < 3)
            return nums[nums.length - 1];
        return nums[nums.length - 3];
    }
}

image

2021-10-08 16:11:34 星期五

剑指 Offer 27. 二叉树的镜像

https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) return root;
        TreeNode t;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            TreeNode poll = queue.poll();
            t = poll.left;
            poll.left = poll.right;
            poll.right = t;
            if (poll.left != null)
            queue.offer(poll.left);
            if (poll.right != null)
            queue.offer(poll.right);
        }
        return root;
    }
}

image

面试题 16.25. LRU 缓存

https://leetcode-cn.com/problems/lru-cache-lcci/

class LRUCache {

    private List<Entry> entries;
    private static int score = 0;

    private int capacity;

    class Entry{
        int k;
        int v;
        int score;

        public Entry(int k, int v) {
            this.k = k;
            this.v = v;
        }


    }
    public LRUCache(int capacity) {
        entries = new ArrayList<>(capacity);
        this.capacity = capacity;
    }

    public int get(int key) {
        for (Entry entry : entries) {
            if (entry.k == key) {
                entry.score = LRUCache.score++;
                return entry.v;
            }
        }
        return -1;
    }

    public void put(int key, int value) {
        Entry entry = new Entry(key, value);
        entry.score = LRUCache.score++;
        int pos = contains(key);
        if (pos != -1){
            entries.set(pos, entry);
            return;
        }
        if (entries.size() == capacity){
            clear();
        }
        entries.add(entry);
    }

    private void clear(){
        entries.sort(new Comparator<Entry>() {
            @Override
            public int compare(Entry o1, Entry o2) {
                return o2.score - o1.score;
            }
        });
        entries.remove(entries.size() - 1);
    }

    private int contains(int key){
        for (int i = 0; i < entries.size(); i++) {
            if (entries.get(i).k == key){
                return i;
            }
        }
        return -1;
    }
}

image

NC4 判断链表中是否有环

https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) return true;
        }
        return false;
    }
}

NC105 二分查找-II

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 如果目标值存在返回下标,否则返回 -1
     * @param nums int整型一维数组 
     * @param target int整型 
     * @return int整型
     */
    public int search (int[] nums, int target) {
        int begin = 0;
        int end = nums.length - 1;
        int med = 0;
        while(begin <= end){
            if(nums[begin] == target) return begin;
            med = (begin + end) / 2;
            if(nums[med] > target){
                end = med - 1;
            }else if(nums[med] < target){
                begin = med + 1;
            }else{
                if(med == 0 || nums[med - 1] != target) return med;
                begin++;
            }
        }
        return -1;

    }
}

NC15 求二叉树的层序遍历

https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if(root == null) return result;
        Queue<TreeNode> q1 = new LinkedList<>();
        Queue<TreeNode> q2 = new LinkedList<>();
        q1.offer(root);
        while(!q1.isEmpty() || !q2.isEmpty()){
            ArrayList<Integer> list = new ArrayList<>();
            while(!q1.isEmpty()){
                TreeNode poll = q1.poll();
                list.add(poll.val);
                if(poll.left != null){
                    q2.offer(poll.left);
                }
                if(poll.right != null){
                    q2.offer(poll.right);
                }
            }
            if(!list.isEmpty())
            result.add(list);
            list = new ArrayList<>();
            while(!q2.isEmpty()){
                TreeNode poll = q2.poll();
                list.add(poll.val);
                 if(poll.left != null){
                    q1.offer(poll.left);
                }
                if(poll.right != null){
                    q1.offer(poll.right);
                }
            }
            if(!list.isEmpty())
            result.add(list);
        }
        return result;
    }
}
posted @ 2021-08-01 10:31  王^.^令  阅读(63)  评论(0)    收藏  举报