力扣算法篇

力扣算法篇

1.两数之和

import java.util.Arrays;
import java.util.HashMap;

/**
 * @Author :张国军
 * @Date :Created in 12:26 2021/1/30
 * @Description : 两数之和
 **/
public class Demo1 {


    public static void main(String[] args) {
        int []array = {2,6,8,9,4,1,99};

        int [] a = twoSun(array,9);
        System.out.println(Arrays.toString(a));



    }


    public static int[] twoSun (int [] nums ,int target){

        HashMap<Integer , Integer> hashMap = new HashMap<>(nums.length-1);

        hashMap.put(nums[0],0);

        for (int i = 1 ; i<nums.length;i++){
            if (hashMap.containsKey(target-nums[i])){
                return new int[] {i,hashMap.get(target-nums[i])};
            }

            hashMap.put(nums[i],i);

        }

        return new int[0];

    }


}

2.两数相加

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
         ListNode root = new ListNode(0);
        ListNode cursor = root;
        int carry = 0;
        while(l1 != null || l2 != null || carry != 0) {
            int l1Val = l1 != null ? l1.val : 0;
            int l2Val = l2 != null ? l2.val : 0;
            int sumVal = l1Val + l2Val + carry;
            carry = sumVal / 10;
            
            ListNode sumNode = new ListNode(sumVal % 10);
            cursor.next = sumNode;
            cursor = sumNode;
            
            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
        
    }
    return root.next;
}
}

root头结点为辅助变量,所以root.next;

3.无重复字符的最长子串

  public static int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        int n = s.length(), max = 0;

        for (int end =0 , start =0;end <s.length();end++){

            char c = s.charAt(end);

            if (map.containsKey(c)){
                start = Math.max(map.get(c),start);
            }

            max = Math.max(max , end - start +1);
            map.put(c,end+1);
        }
        return max;

    }

start = Math.max(map.get©,start);这句话的意思是返回大的下标;

max = Math.max(max , end - start +1);这句话的意思是返回有效字符的个数;

map.put(c,end+1);替换掉前一个数,更新下标;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值