• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

Shopee代码准备

开发技术 开发技术 5天前 7次浏览

相交链表

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();
        }
}

程序员灯塔
转载请注明原文链接:Shopee代码准备
喜欢 (0)