力扣算法篇
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);替换掉前一个数,更新下标;