leetcode春节假期刷题(一)


很久没刷题了,现在刷一刷题找一找手感

刷题中常用到的函数

Arrays.sort(num) 排序数组 假如需要按照自己定义的排序的话 Arrary.sort(num,比较器)
map.containsKey(key) map中是否有key
Map.Entry entry : map.entrySet() 遍历map的方法
Character PriorityQueue

Leetcode 1

 Map map = new HashMap();
        for(int i=0;itarget){
                right--;
            }else{
                break;
            }
        }
        return new int[]{map.get(nums[left]),map.get(nums[right])};

**当有相同元素的时候样例错误 **
修改代码

  Map map = new HashMap();

        for(int i=0;i

需要思考的边界问题?
不能用上述的原因是map.put(num[i],i),相同值会被覆盖

Leetcode 2

int carray = 0;
       int first,second,sum;
       ListNode head = new ListNode();
       ListNode cur=head.next;
       while(l1!=null||  l2!=null){
           first= l1!=null?l1.val:0;
           second = l2!=null? l2.val:0;
           sum =first+second +carray;
           carray = sum/10;
           sum = sum%10;
           if(cur!=null){
              cur.next=  new ListNode(sum);
              cur = cur.next;
           }else{
               cur = new ListNode(sum);
                head.next=cur;
           }
           if(l1!=null){
               l1=l1.next;
           }
           if(l2!=null){
               l2=l2.next;
           }
       }
       if(carray!=0){
           ListNode node = new ListNode(1);
           cur.next= node ;
       }

       return head.next;

需要思考的边界问题
关于java中的深浅拷贝 深拷贝 连内存一起复制 ,浅拷贝只是占用同一片地址空间
在引用对象中 = 属于浅拷贝,将右边对象的内存地址 给与左边对象

leetcode 3

Map map = new HashMap();
       int maxLen=0;
       for(int i=0;i m :map.entrySet()){
                 if(m.getValue()

执行出错,需要修改问题
自己修改后

int max=0,start=0;
       Map map = new HashMap();

       for(int i = 0;i


依然有bug
最终

HashMap map = new HashMap<>();
        int max = 0, start = 0;
        for (int end = 0; end < s.length(); end++) {
            char ch = s.charAt(end);
            if (map.containsKey(ch)){
                start = Math.max(map.get(ch)+1,start);
            }
            max = Math.max(max,end - start + 1);
            map.put(ch,end);
        }
        return max;

需要思考的边界问题
同样是维护一个窗口,下面的写法更加简洁,下面只是维护了俩个变量。
start = Math.max(map.get(c)+1,start) 和start = map.get(c)+1的的区别.

LeetCode 704

迭代版本

 int left =  0 ,right = nums.length-1; 
        while(left<=right){
            int mid = left+ (right-left)/2; 
            if(nums[mid]target){
                right= mid-1;   
            }else{
                return  mid;
            }
        }

        return  -1;

递归版本

public int search(int [] nums ,int left, int right ,int target ){
       if(left>right){
           return -1;
       }
       int mid  = left+(right-left)/2;
       int res =0;
       if(nums[mid]target){
          res  = search(nums,left,mid-1,target);
       }else{
           return  mid;
       }
       return res;
   }