面试遇到手撕代码问题

1.字符串相加(leetcode 415)
class Solution {
    public String addStrings(String num1, String num2) {
        int cover = 0;//进位
        int n1 = num1.length()-1;
        int n2 = num2.length()-1;
        StringBuilder sb = new StringBuilder();

        while(n1 >= 0 || n2 >= 0 || cover > 0){
            int count1 =0,count2 = 0;
            if(n1 >= 0) count1 = (num1.charAt(n1--) -'0');
            if(n2 >= 0) count2 = (num2.charAt(n2--) -'0');
            int sum = count1 + count2 + cover;
            sb.append(sum % 10);
            cover = sum / 10;
        }
        return sb.reverse().toString();
    }
}

2.字符串相乘 (leetcode 43)
class Solution {
    public String multiply(String num1, String num2) {
        int n1 = num1.length();
        int n2 = num2.length();
        int [] res = new int[n1 + n2];
        for(int i = n1 - 1;i >=0;i--){
            for(int j = n2 - 1;j >= 0;j--){
                int count1 = (num1.charAt(i) - '0');
                int count2 = (num2.charAt(j) - '0');
                int low = i + j + 1;
                int high = i + j;
                int sum = count1 * count2 + res[low];
                res[low] = sum % 10;
                res[high] += sum / 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        for(int num : res){
            if(sb.length() == 0 && num == 0){//去除最高位0
                continue;
            }
            sb.append(num);
        }
        if(sb.length() == 0) return "0";
        return sb.toString();
    }
}

3.Lru (leetcode 146)
class LRUCache {
    class Node{
        private int key;
        private int val;
        private Node prev;
        private Node next;
        public Node(int key,int val){
            this.key = key;
            this.val =val;
        }
    }
    private final HashMap<Integer,Node>hs;
    private final Node head;
    private final Node tail;
    private int capacity;
    public LRUCache(int capacity) {
        this.capacity =capacity;
        hs = new HashMap<>();
        head = new Node(-1,-1);
        tail = new Node(-1,-1);
        head.next = tail;
        tail.prev = head;
    }
    
    public int get(int key) {
        if(hs.containsKey(key)){
            Node node = hs.get(key);
            removeTohead(node);
            return node.val;
        }
        return -1;
    }
    
    public void put(int key, int value) {
        if(hs.containsKey(key)){
            Node node = hs.get(key);
            node.val = value;
            removeTohead(node);
            return;
        }
        if(hs.size()==capacity){
            Node node = tail.prev;
            removeNode(node);
            hs.remove(node.key);
        }
        Node node = new Node(key,value);
        addToHead(node);
        hs.put(key,node);
    }
    private void addToHead(Node node){
        node.prev =head;
        node.next = head.next;
        head.next.prev = node;
        head.next = node;
    }
    private void removeTohead(Node node){
        removeNode(node);
        addToHead(node);
    }
    private void removeNode(Node node){
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }
}

/**
 * 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);
 */

4.合并两个有序链表 (leetcode 21)
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummy =new ListNode();
        ListNode pre = dummy;
        while(list1!=null&&list2!=null){
            if(list1.val<list2.val){
                pre.next = list1;
                list1 = list1.next;
            }else{
                pre.next = list2;
                list2 =list2.next;
            }
                pre = pre.next;
        }
        if(list1!=null){
            pre.next = list1;
        }
        if(list2!=null){
            pre.next = list2;
        }
        return dummy.next;
    }
}

5.重排链表(leetcode 143)
/**
 * Definition for singly-linked list.
 * 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 Solution {
    public void reorderList(ListNode head) {
        List<ListNode> list = new ArrayList<>();
        ListNode cur = head;
        while(cur != null){
            list.add(cur);
            cur = cur.next;
        }
        int left = 0;
        int right = list.size() - 1;
        while(left < right){
            list.get(left).next = list.get(right);
            left++;
            list.get(right).next = list.get(left);
            right--;
        }
        list.get(left).next = null;
    }
}

6.简化路径(leetcode 71)
class Solution {
    public String simplifyPath(String path) {
        String[] parts = path.split("/");
        Deque<String> queue = new LinkedList<>();
        for(String part : parts){
            if("..".equals(part)){
                if(!queue.isEmpty()) queue.pollLast();
            }else if(part.length() > 0 && !".".equals(part)){
                queue.offerLast(part);
            }
        }
        StringBuilder sb = new StringBuilder();
        if(queue.isEmpty()) sb.append("/");
        else{
            while(!queue.isEmpty()){
                if(!queue.isEmpty()){
                    sb.append("/").append(queue.pollFirst());
                }
            }
        }
        return sb.toString();
    }
}

7.形成三的最大倍数(leetcode 1363)
class Solution {
    public String largestMultipleOfThree(int[] digits) {
        Arrays.sort(digits);
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        int sum = 0;
        for(int i = 0;i < digits.length;i++){
            int num = digits[i];
            sum += num;
            if(num % 3 == 1){
                list1.add(i);//只添加索引,防止出现多个元素同时出现的情况,跳过元素时,操作困难,只用索引,避免问题.
            }else if(num % 3 == 2){
                list2.add(i);
            }
        }       
        sum = sum % 3;
        if(sum == 1){
            if(!list1.isEmpty()){
                return remove(digits,list1.get(0),-1);
            }else{
                return remove(digits,list2.get(0),list2.get(1));
            }
        }else if(sum == 2){
            if(! list2.isEmpty()){
                return remove(digits,list2.get(0),-1);
            }else{
                return remove(digits,list1.get(0),list1.get(1));
            }
        }
         return remove(digits,-1,-1);
    }
    private String remove(int []digits,int first,int second){
        StringBuilder sb = new StringBuilder();
        for(int i = digits.length-1;i >= 0;i--){//已排序,递减遍历得到最大值
            if(i == first ||i == second){//跳过
                continue;
            }else{
                sb.append(digits[i]);
            }
        }
        //可以去除特殊情况,例如只有0,或者没有元素,直接返回"".
        return sb.length() > 0 && sb.charAt(0) == '0' ? "0" : sb.toString();
    }
}

8.最小覆盖子串(leetcode 76)
class Solution {
    public String minWindow(String s, String t) {
        HashMap<Character,Integer> hms = new HashMap<>();
        HashMap<Character,Integer> hmt = new HashMap<>();
        //1.统计t中每个字符的个数
        for(int i = 0;i < t.length();i++){
            char ch = t.charAt(i);
            hmt.put(ch,hmt.getOrDefault(ch,0) + 1);
        }
        int count = 0;//用于记录s中匹配t的字符数
        int length = Integer.MAX_VALUE;
        String ans = "";
        //i控制末尾,j控制开始
        for(int i = 0,j= 0; i < s.length();i++){
            char ch = s.charAt(i);
            hms.put(ch,hms.getOrDefault(ch,0) + 1);
            //2.如果t中存在第i个字符,判断当前s中第i个字符匹配个数是否小于t,小于数量++,表明未完全匹配
            if( hmt.containsKey(ch) && hms.get(ch) <= hmt.get(ch)) count++;
            //3.缩小范围:当t中不包含该j字符的时候或者该字符多了,都可以后移;
            while(j < i && (! hmt.containsKey(s.charAt(j)) || 
            hms.get(s.charAt(j)) > hmt.get(s.charAt(j)))){
                hms.put(s.charAt(j),hms.get(s.charAt(j)) -1);
                j++;
            }
            //4.当计数个数相同时,且长度小于length时,说明匹配成功
            if(count == t.length() && (i-j + 1) < length){
                length = i -j + 1;
                ans = s.substring(j,i+1);
            }
        }
        return ans;
    }
}

9. 连续数组(leetcode 525)
class Solution {
    public int findMaxLength(int[] nums) {
        //核心思想:数值不变思想,如果0和1的数量相等的话,值++后--应该等于原值,对于0进行--,对于1进行++
        //所以只需要存储记录每个值对应下标就好了,当出现了同样下标时,两者相减就是长度
        //对于数值0的情况需要初始化为-1,例如01,1 -(-1) = 2如果,初始化为0的情况会少1.
        HashMap<Integer,Integer> hm = new HashMap<>();
        int count = 0;
        hm.put(0,-1);
        int ans = 0;
        for(int i = 0;i < nums.length;i++){
           nums[i] =  nums[i] == 0 ? count-- : count ++;
            if(hm.containsKey(count)){//说明该区间有连续的01值了
                ans = Math.max(ans,i - hm.get(count));
            }else{
                hm.put(count,i);
            }
        }
        return ans;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

xzkyd outpaper

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

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

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

打赏作者

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

抵扣说明:

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

余额充值