算法 & 数据结构面试篇

二分查找:(单调递增或递减、存在上下界、能够通过索引访问)

class Solution {
    fun search(nums: IntArray, target: Int): Int {
        if (nums.size == 0) return -1
        var start = 0
        var end = nums.size - 1
        var middle = 0
        while (start <= end) {
            middle = (start + end) / 2
            when {
                nums[middle] == target -> {
                    return middle
                }
                nums[middle] > target -> {
                    end = middle - 1
                }
                else -> {
                    start = middle + 1
                }
            }
        }
        return -1
    }
}

字符串转整数

    int strToInt(String str) {
        if (str == null || str.isEmpty()) return 0;
        char[] chars = str.toCharArray();
        int index = 0, n = str.length(), sign = 1, res = 0;
        // 处理前置空格
        while (index < n && chars[index] == ' ') {
            ++index;
        }
        // 处理符号
        if (index < n && (chars[index] == '+' || chars[index] == '-')) {
            sign = chars[index++] == '+' ? 1 : -1;
        }
        // 处理数字
        while (index < n && Character.isDigit(chars[index])) {
            int digit = chars[index] - '0';
            // 判断是否溢出
            if (res > (Integer.MAX_VALUE - digit) / 10) {
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            res = res * 10 + digit;
            ++index;
        }
        return res * sign;
    }

最长公共前缀

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String prefix = strs[0];
        int count = strs.length;
        for (int i = 1; i < count; i++) {
            prefix = longestCommonPrefix(prefix, strs[i]);
            if (prefix.length() == 0) {
                break;
            }
        }
        return prefix;
    }

    public String longestCommonPrefix(String str1, String str2) {
        int length = Math.min(str1.length(), str2.length());
        int index = 0;
        while (index < length && str1.charAt(index) == str2.charAt(index)) {
            index++;
        }
        return str1.substring(0, index);
    }
}

反转链表:只要保证cur不为空

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode nex = null;
        while(cur != null) {
            nex = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nex;
        }
        return pre;
    }

    // 双向列表
    private ListNode reverseList(ListNode head) {
        ListNode prev = head;
        ListNode cur = head.next;
        head.next = null;
        while(cur != null){
            ListNode temp = cur.next;
            cur.next = prev;
            prev.prev = cur;
            prev = cur;
            cur = temp;
        }
        return prev;
    }
}

环形链表:HashSet、快慢指针

public class Solution {
    public boolean hasCycle(ListNode head) {
        // if(head == null) return false;
        // ListNode cur = head;
        // HashSet<ListNode> hashSet = new HashSet<>();
        // while(cur != null) {
        //     if(hashSet.contains(cur)) return true;
        //     hashSet.add(cur);
        //     cur = cur.next;
        // }
        // return false;
        ListNode low = head, fast = head;
        while(fast != null) {
            low = low.next;
            fast = fast.next;
            if(fast == null) return false;
            fast = fast.next;
            if(fast == low) return true;
        }
        return false;
    }
}

有效的括号:需要后面的括号作为Key、需要实时判断栈是否为空

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        Map<Character, Character> map = new HashMap<>();
        map.put(')', '(');
        map.put('}', '{');
        map.put(']', '[');
        for (int i = 0; i < s.length(); i++) {
            if(!map.containsKey(s.charAt(i))) {
                stack.push(s.charAt(i));
            } else {
                //忘记判断栈是否为空了
                if(stack.isEmpty()) return false;
                if(!stack.pop().equals(map.get(s.charAt(i)))) return false;
            }
        }
        return stack.isEmpty();
    }
}

二数之和:暴力循环、HashMap

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> hashMap = new HashMap<>();
    int length = nums.length;
    for(int i = 0; i < length; i++) {
        int des = target - nums[i];
        if(hashMap.containsKey(des)) {
            return new int[] {hashMap.get(des), i};
        }
        hashMap.put(nums[i], i);
    }
    throw new IllegalArgumentException("no result");
}

快速排序

public static void quickSort(int[] arr){
    qsort(arr, 0, arr.length-1);
}
private static void qsort(int[] arr, int low, int high){
    if (low >= high) return;
    int pivot = partition(arr, low, high);      //将数组分为两部分
    qsort(arr, low, pivot-1);                   //递归排序左子数组
    qsort(arr, pivot+1, high);                  //递归排序右子数组
}
private static int partition(int[] arr, int low, int high){
    int pivot = arr[low];     //基准
    while (low < high){
        while (low < high && arr[high] >= pivot) --high;
        arr[low]=arr[high];             //交换比基准大的记录到左端
        while (low < high && arr[low] <= pivot) ++low;
        arr[high] = arr[low];           //交换比基准小的记录到右端
    }
    //扫描完成,基准到位
    arr[low] = pivot;
    //返回的是基准的位置
    return low;
}

遍历二叉树(前序、中序、后序)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    public List<Integer> preOrderTraversal(TreeNode root) {
        //traversal
        List<Integer> list = new LinkedList<Integer>();
        if(root == null) return list;
        list.add(root.val);
        list.addAll(preorderTraversal(root.left));
        list.addAll(preorderTraversal(root.right));
        return list;
        
        //non-traversal
        List<Integer> list = new LinkedList<Integer>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            list.add(cur.val);
            //这里不要糊涂,应该是右孩子先进栈
            if (cur.right != null) stack.push(cur.right);
            if (cur.left != null) stack.push(cur.left);
        }
        return list;
    }

    public List<Integer> inOrderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new LinkedList<>();
        if(root == null) return list;
        TreeNode cur = root;
        //如果cur不为空,一直往左压栈,访问栈顶,右孩子入栈
        while(!stack.isEmpty() || cur != null) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            list.add(cur.val);
            cur = cur.right;
        }
        return list;
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode lastVisit = null;
        while(!stack.isEmpty() || cur != null) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.peek();
            if (cur.right == null || cur.right == lastVisit) {
                list.add(cur.val);
                lastVisit = stack.pop();
                cur = null;
            } else {
                cur = cur.right;
            }
        }
        return list;
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<Integer>();
            int currentLevelSize = queue.size();
            for (int i = 1; i <= currentLevelSize; ++i) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            ret.add(level);
        }
        
        return ret;
    }

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            int leftHeight = maxDepth(root.left);
            int rightHeight = maxDepth(root.right);
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            ans++;
        }
        return ans;
    }
}

X的N次方

class Solution {
    public double customPower(double x, int n) {
        return n >= 0 ? customMultiple(x, n) : 1.0 / customMultiple(x, -n);
    }
    public double customMultiple(double x, int n) {
        if (n == 0) {
            return 1.0;
        }
        double y = multiple(x, n / 2);
        return n % 2 == 0 ? y * y : y * y * x;
    }
}

乘积最大子数组

class Solution {
    public int maxProduct(int[] nums) {
        int length = nums.length;
        int[] maxF = new int[length];
        int[] minF = new int[length];
        System.arraycopy(nums, 0, maxF, 0, length);
        System.arraycopy(nums, 0, minF, 0, length);
        for (int i = 1; i < length; ++i) {
            maxF[i] = Math.max(maxF[i - 1] * nums[i], Math.max(nums[i], minF[i - 1] * nums[i]));
            minF[i] = Math.min(minF[i - 1] * nums[i], Math.min(nums[i], maxF[i - 1] * nums[i]));
        }
        int ans = maxF[0];
        for (int i = 1; i < length; ++i) {
            ans = Math.max(ans, maxF[i]);
        }
        return ans;
    }
}

最大子序列和

class Solution {
    public int maxSubArray(int[] nums) {
        int pre = 0, maxAns = nums[0];
        for (int x : nums) {
            pre = Math.max(pre + x, x);
            maxAns = Math.max(maxAns, pre);
        }
        return maxAns;
    }
}

排序算法

  • 冒泡排序:O(n2)、O(1)
  • 选择排序 O(n2)、O(1)
  • 插入排序 O(n2)、O(1)
  • 归并排序 O(nlogn)、O(n)
  • 快速排序 O(nlogn)、O(logn)
  • 堆排序 O(nlogn)、O(1)
  • 希尔排序 O(n1.5)、O(1) 升级版的插入排序
  • 计数排序 O(n)、O(n)
  • 桶排序 O(n)、O(n)

切题四件套

Clarification、Possible solutions、Coding、Test cases

常用数据结构

数组、链表、队列、栈、堆、哈希表、树、二叉查找树、字母树、LRU缓存

常用算法

递归、贪心、分治、广度优先搜索、深度优先搜索、二叉树遍历、动态规划、二分查找、图

时间/空间复杂度

O(1)、O(logn)、O(n)、O(nlogn)、O(n2)、O(n3)、O(2n)、O(n!)

常见算法复杂度

二分查找:O(logn)、二叉树遍历:O(n)、归并排序:O(nlogn)

做题之前一定要想时间/空间复杂度

MapputgetremovecontainsKeykeySetentrySetclearisEmptysize
CollectionaddaddAllremoveremoveAllcontainscontainsAllclearisEmptysize
Set
Listget
Stackpushpeekpop
Queueaddpeekpoll
Deque

addFrist

addLast

peekFirst

peekLast

pollFirst

pollLast

String:charAt、toCharArray、Arrays.sort、valueOf

涉及到获取操作一定要想到判空

LinkedList 实现了 List、Queue、Deque

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

little-sparrow

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值