Shopee代码准备

相交链表

160
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null)return null;
        int la =0,lb =0,dlt=0;
        ListNode ta = headA,tb = headB;
        while(ta!=null){la++;ta=ta.next;}
        while(tb!=null){lb++;tb= tb.next;}
        dlt = la-lb;
        ta = headA ;tb = headB;
        while(dlt!=0){
            if(dlt>0){ta=ta.next;dlt--;}
            if(dlt<0){tb=tb.next;dlt++;}
        }
        while(ta!=tb){
            ta = ta.next;
            tb = tb.next;
        }
        return ta;
    }
}

704二分查找

class Solution {
    public int search(int[] nums, int target) {
        int l = 0,r = nums.length-1;
        while(l<=r){
            int m = (l+r)/2;
            if(nums[m]<target){
                l = m+1;
            }
            else if(nums[m]>target) {
                r = m-1;
            }
            else{
                return m;
            }
        }
        return -1;
    }
}

232 栈实现队列

class MyQueue {
LinkedList<Integer> in,out;
        public MyQueue(){
            in = new LinkedList<>();
            out = new LinkedList<>();
        }

        public void push(int x){
            while(!out.isEmpty()){
                in.push(out.pop());
            }
            in.push(x);
        }

        public int pop(){
            while(!in.isEmpty()){
                out.push(in.pop());
            }
            return out.pop();
        }

        public int peek(){
            while(!in.isEmpty()){
                out.push(in.pop());
            }
            return out.peek();
        }

        public boolean empty(){
            return in.isEmpty()&&out.isEmpty();
        }
}

两数之和

class Solution {
    public int[] twoSum(int[] nums, int target) {
       int[] temp = new int[nums.length];
        Map<Integer,Integer> dict = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            int c = nums[i];
            Integer idx = dict.get(target-c);
            if(idx==null){
                dict.put(c,i);
            }
            else{
                return new int[]{i,idx};
            }
        }
        return new int[]{};
    }
}
原文地址:https://www.cnblogs.com/zhouyu0-0/p/14869644.html