练习02/23

 

话说第一次用java写题目,磕磕绊绊的,书写习惯还是原来的- - 好丑

 

https://leetcode-cn.com/problems/two-sum/

map记录val的i,然后因为只有唯一答案,所以顺着找就可以了

练习02/23
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> ma=new HashMap<Integer,Integer>();
        for(Integer i=0;i<nums.length;i++){
            if(ma.containsKey(target-nums[i])){
                return new int[]{ma.get(target-nums[i]),i};
            }
            ma.put(nums[i],i);
        }
        return new int[0];
    }
}
View Code

https://leetcode-cn.com/problems/add-two-numbers/

up作为进位,如果l1或者l2已经没有next的话,就初始一个0继续递归下去,如果l1和l2都没了但还有一个进位,就再new一个值为1的节点

练习02/23
/**
 * 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 ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int sum=l1.val+l2.val;

        ListNode nxt1=l1.next;
        ListNode nxt2=l2.next;
        ListNode nxt=null;
        int up=sum/10;
        if(nxt1!=null||nxt2!=null){
            if(nxt1==null) nxt1=new ListNode(0);
            if(nxt2==null) nxt2=new ListNode(0);
            nxt1.val+=up;
            nxt=addTwoNumbers(nxt1,nxt2);
        }
        else if(up==1){
            nxt=new ListNode(1);
        }
        return new ListNode(sum%10,nxt);
    }
}
View Code

https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

如果遇到重复字符,就需要判断是否要重新调整字符串起始位置(字符在之前出现过,但并不包括在当前字符串里,不需要移动st)

练习02/23
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int maxn=0;
        Map<Character,Integer> ma=new HashMap<Character,Integer>();
        for(int ed=0,st=0;ed<s.length();ed++){
            if(ma.containsKey(s.charAt(ed))){
                st=ma.get(s.charAt(ed))>st?ma.get(s.charAt(ed)):st;
            }
            maxn=maxn>(ed-st+1)?maxn:(ed-st+1);
            ma.put(s.charAt(ed),ed+1);
        }
        return maxn;
    }
}
View Code

https://leetcode-cn.com/problems/median-of-two-sorted-arrays/

暴力了暴力了,长度为奇数要找到l/2+1的值,偶数还需要标记一下l/2的值

练习02/23
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int i=0,j=0,kk=0;
        int l1=nums1.length,l2=nums2.length;
        int k=(l1+l2)/2;
        int num=0,mark=0;
        while(true){
            int a=0,b=0;
            a=(i>=l1)?Integer.MAX_VALUE:nums1[i];
            b=(j>=l2)?Integer.MAX_VALUE:nums2[j];
            if(a<b) i++;
            else j++;
            kk++;
            num=a<b?a:b;
            if(kk>k)break;
            mark=a<b?a:b;
        }
        if((l1+l2)%2==1){
            return (double)num;
        }
        return (double)(num+mark)/2.0;
    }
}
View Code

 

上一篇:JAVA异常


下一篇:深度分析Dubbo SPI源码,扩展Dubbo Validation (groups)