面试常考算法-完整代码记录

无重复字符的最长子串无重复字符的最长子串完整代码
反转链表反转链表完整代码
数组中的第K个最大元素215. 数组中的第K个最大元素完整代码
最大子数组和53. 最大子数组和完整代码
合并两个有序链表21. 合并两个有序链表完整代码
全排列46. 全排列完整代码
二分查找704. 二分查找完整代码
最长公共子序列1143. 最长公共子序列完整代码
最长递增子序列300. 最长递增子序列完整代码
字符串相加415. 字符串相加
平均数为k的最长连续子数组牛客美团笔试
和为 K 的子数组560. 和为 K 的子数组
删除排序链表中的重复元素83. 删除排序链表中的重复元素
合并区间56. 合并区间
LRU 缓存146. LRU 缓存

反转链表

public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) {
            this.val = val;
      }
      ListNode(int val, ListNode next) {
            this.val = val; this.next = next;
      }
}
class Test{
      public static ListNode solve(ListNode head){
            ListNode pre = null;
            ListNode cur = head;
            while(cur != null){
                  ListNode temp = cur.next;  //记录后继指针用于后续更新
                  cur.next = pre;  //当前节点指针转向
                  //更新
                  pre = cur;
                  cur = temp;
            }
            return pre;
      }

      public static void main(String[] args) {
            ListNode node4 = new ListNode(4, null);
            ListNode node3 = new ListNode(3, node4);
            ListNode node2 = new ListNode(2, node3);
            ListNode node1 = new ListNode(1, node2);

            ListNode res = solve(node1);
            while(res != null){
                  System.out.print(res.val + " ");
                  res = res.next;
            }
      }
}

合并两个有序链表

public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) {
            this.val = val;
      }
      ListNode(int val, ListNode next) {
            this.val = val; this.next = next;
      }
}
class Test{
      public static ListNode merge(ListNode l1, ListNode l2){
            //新建节点可以省略头指针为空的处理
            ListNode pre = new ListNode(-1);
            ListNode cur = pre;
            while(l1 != null && l2 != null){
                  if(l1.val < l2.val){
                        cur.next = l1;
                        l1 = l1.next;
                  }else{
                        cur.next = l2;
                        l2 = l2.next;
                  }
                  cur = cur.next;
            }
            if(l1 != null) cur.next = l1;
            if(l2 != null) cur.next = l2;
            return pre.next;
      }

      public static void main(String[] args) {
            ListNode node4 = new ListNode(4, null);
            ListNode node3 = new ListNode(3, node4);
            ListNode node2 = new ListNode(2, node3);
            ListNode node1 = new ListNode(1, node2);

            ListNode node7 = new ListNode(7, null);
            ListNode node6 = new ListNode(2, node7);
            ListNode node5 = new ListNode(0, node6);

            ListNode res_merge = merge(node1, node5);
            while(res_merge != null){
                  System.out.print(res_merge.val + " ");
                  res_merge = res_merge.next;
            }
      }
}

字符串相加

public class AddString {
    public static String solve(String s1, String s2){
        int l1 = s1.length() - 1;
        int l2 = s2.length() - 1;
        StringBuffer res = new StringBuffer();
        int sum = 0, c = 0, curr = 0;
        while(l1 >= 0  || c != 0 || l2 >= 0){
            int num1 = l1 >= 0 ? (s1.charAt(l1 --) - '0') : 0;
            int num2 = l2 >= 0 ? (s2.charAt(l2 --) - '0') : 0;
            sum  = num1 + num2 + c;
            curr = sum % 10;
            c = sum/10;
            res.append(curr);
        }
        return res.reverse().toString();
    }
    public static void main(String[] args) {
        String s1 = "11";
        String s2 = "999";
        String res = solve(s1, s2);
        System.out.println(res.toString());
    }
}

和为k的子数组个数

import java.util.*;

public class Main {
    
    public static int addK(int[] nums, int k){
        Map<Integer, Integer> map = new HashMap<>();
        //初始化,和为0的子数组的个数为1(空数组)
        map.put(0, 1);
        int res = 0;
        int sum = 0;
        for(int num : nums){
            sum += num;
            if(map.containsKey(sum - k)){
                res += map.get(sum - k);
            }
            int temp = map.containsKey(sum) ? map.get(sum) + 1 : 1;
            map.put(sum, temp);
        }
        return res;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int[] nums = new int[n];
        nums[0] = 0;
        for(int i = 0; i < n; i ++){
            nums[i] = sc.nextInt();
        }

        int res = addK(nums, k);
        System.out.println(res);
    }
}

平均数为k的最长子数组

import java.util.*;

/**
 * 给定n个正整数组成的数组,求平均数正好等于 k 的最长连续子数组的长度
 */

public class Main {
    public static int solve(int[] nums, int k, int n){
        int res = 0;
        long  sum = 0;
        Map<Long, Integer> map = new HashMap<Long, Integer>();
        map.put(0L, 0);
        for(int i = 1; i <= n; i ++){
            sum += nums[i] - k;
            if(map.containsKey(sum)){
                //i位置的元素是不属于结果集的
                res = Math.max(res, i - map.get(sum));
            }else{
                map.put(sum, i);
            }
        }
        return res == 0 ? -1 : res;
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), k = sc.nextInt();
        int[] nums = new int[n + 1];
        nums[0] = 0;
        for(int i = 1; i <= n; i ++){
            nums[i] = sc.nextInt();
        }

        int res = solve(nums, k, n);
        System.out.println(res);
    }
}

删除排序链表中的重复元素

public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) {
            this.val = val;
      }
      ListNode(int val, ListNode next) {
            this.val = val; this.next = next;
      }
}
class Test{

      public ListNode deleteRepeat(ListNode head) {
            if(head == null){
                  return null;
            }
            //删除操作
            while(head.next != null && head.val == head.next.val){
                  head.next = deleteDuplicates(head.next.next);
            }
            head.next = deleteDuplicates(head.next);

            return head;
      }

      public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return head;
        }

        ListNode cur = head;
        while (cur.next != null) {
            if (cur.val == cur.next.val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }

        return head;
    }

      public static void main(String[] args) {
            ListNode node4 = new ListNode(4, null);
            ListNode node3 = new ListNode(4, node4);
            ListNode node2 = new ListNode(4, node3);
            ListNode node1 = new ListNode(1, node2);


            ListNode res_delete = deleteRepeat(node1);
            while(res_merge != null){
                  System.out.print(res_merge.val + " ");
                  res_merge = res_merge.next;
            }
      }
}

区间合并

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Merge {
    public static int[][] merge(int[][] arrs){
        List<int[]> res = new ArrayList<>();
        //按照起点排序
        Arrays.sort(arrs, (x,y) -> Integer.compare(x[0], y[0]));
        res.add(new int[]{arrs[0][0], arrs[0][1]});
        for(int[] arr : arrs){
            int l = arr[0];
            int r = arr[1];
            if(res.get(res.size() - 1)[1] < l){
                res.add(new int[]{l, r});
            }else{
                int nowR = Math.max(res.get(res.size() - 1)[1], r);
                res.get(res.size() - 1)[1] = nowR;
            }
        }
        return res.toArray(new int[res.size()][]);
    }
    public static void main(String[] args) {
        int[][] arr = {
                {1,3},
                {2,4},
                {5,6},
                {8,10},
        };
        int[][] res = merge(arr);
        for(int[] ar : res){
            System.out.println(ar[0] + " " + ar[1]);
        }

    }
}

LRU 缓存

import java.util.HashMap;
import java.util.Map;

class LRUCache {
    //定义双向链表
    class DLinkList {
        int key;
        int value;
        DLinkList pre, next;
        public DLinkList() { }
        public DLinkList(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    //通过哈希表操作cache
    Map<Integer, DLinkList> cache = new HashMap<Integer, DLinkList>();
    //cache当前长度
    int cur_len;
    //容量
    int capacity;
    //使用虚拟表尾表头
    DLinkList head, tail;

    /**
     * LRU构造函数
     * @param capacity
     */
    public LRUCache(int capacity) {
        this.cur_len = 0;
        this.capacity = capacity;
        //构造虚拟表头和虚拟表尾
        head = new DLinkList();
        tail = new DLinkList();
        head.next = tail;
        tail.pre = head;
    }
    /**
     * 缓存获取元素,存在返回value, 不存在返回-1
     * @param key
     * @return
     */
    public int get(int key) {
        int res = -1;
        //通过哈希表查询cache
        DLinkList node = cache.get(key);
        //cache中没有查询的元素

        //cache中存在查询的元素
        if (node != null) {
            res = node.value;
            //将元素移动到表头
            moveToHead(node);
        }
        return res;
    }
    /**
     * 向缓存中添加新的元素
     * @param key
     * @param value
     */
    public void put(int key, int value) {
        //查询缓存
        DLinkList node = cache.get(key);
        //缓存中未查询到数据
        if (node == null) {
            DLinkList newNode = new DLinkList(key, value);
            //添加到哈希表
            cache.put(key, newNode);
            //将新添加的元素放到表头
            addToHead(newNode);
            cur_len ++;
            //缓存容量处理
            while (cur_len > capacity) {
                //删除链表尾部的元素
                DLinkList tailNode = removeTail();
                //删除对应的哈希表中的元素
                cache.remove(tailNode.key);
                cur_len --;
            }
        } else {
            //缓存中已经存在新添加的元素
            //元素移动到表头
            moveToHead(node);
            //更新value
            node.value = value;
        }
    }
    /**
     * 将元素移动到表头
     * @param node
     */
    private void moveToHead(DLinkList node) {
        //删除链表中的node
        removeNode(node);
        //表头添加元素
        addToHead(node);
    }
    /**
     * 链表删除元素
     * @param node
     */
    private void removeNode(DLinkList node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }
    /**
     * 表头添加元素
     * @param node
     */
    private void addToHead(DLinkList node) {
        //    head <=> tail
        //通过虚拟表头添加元素
        node.next = head.next;
        node.pre = head;
        //   head <- node -> tail
        head.next.pre = node;
        head.next = node;
        //   head <=> node <=> tail
    }
    /**
     * 表尾删除元素
     * @return
     */
    private DLinkList removeTail() {
        //通过虚拟表尾获取表尾元素
        DLinkList tailNode = tail.pre;
        //删除元素
        removeNode(tailNode);
        return tailNode;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值