LeetCode热题100道-Day01
两数之和
- 将target-nums[i] 作为k,i为v 存入HashMap, 遍历nums,看k是否存在即可找到两个数的下下标
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.get(nums[i])!=null){
return new int[]{map.get(nums[i]),i};
}
map.put(target-nums[i],i);
}
return new int[]{};
}
}
两数相加
- 定义两个首尾指针,判断l1、l2都不为空时,将其值相加再加进位得c,新节点的值为c%10, 判断c的预留值,遍历至两个链表都为null,再判断c>0,是否创建新结点。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode list=null;
ListNode p = null;
int c=0;
while(l1!=null||l2!=null){
if (l1!=null){
c += l1.val;
}
if(l2!=null){
c += l2.val;
}
if(list==null){
list = new ListNode(c%10);
p = list;
}else {
list.next =new ListNode(c%10);
list = list.next;
}
c = c>=10?1:0;
l1 = l1 == null? null:l1.next;
l2 = l2 == null? null:l2.next;
if(l1==null&&l2==null&&c>0){
list.next =new ListNode(c);
}
}
return p;
}
}
最长无重复子串
- 使用滑动窗口思想,定义两个start,end指针,将end,下标存入map中,判断end是否存在map中,是则移动窗口 start = max(map,get(s.charAt(end)+1,strat),再比较子串的大小,将新的end下标存入map;
- 当j在[i,j)中存在时,则将start移至存在的位置,例如:"dvdf",end为第二个d时,将start从map.get('d')移动到map.get('d')+1的位置,
class Solution {
public int lengthOfLongestSubstring(String s) {
int ans = 0;
Map<Character, Integer> map = new HashMap<>();
for (int end=0,start = 0; end < s.length(); end++) {
char aphla = s.charAt(end);
if (map.containsKey(aphla)){
start = Math.max(start,map.get(aphla));
}
map.put(aphla,end+1);
ans = Math.max(ans,end-start+1);
}
return ans;
}
}