2020.9.17到2020.9.21的力扣
1.两数之和
2020.9.17更新
暴力解法
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[j] == (target - nums[i])){
return new int[]{i,j};
}
}
}
IllegalArgumentException("No two sum solution");
}
}
双指针法
class Solution{
public int twoSum(int[] nums,int target){
//先创建一个hashmap
Map<Integer, Integer>map = new HashMap<>();
//把nums数组里的值put进去
for(int i = 0;i < nums.length;i++){
map.put(nums[i], i);
}
//
for(int i =0;i < nums.length;i++){
int complement = target - nums[i];
if(map.containsKey(complement)&&map.get(complement) != i){
return new int[]{i, map.get(complement)};
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
/**********************************************************************************************************************************************/
2020.9.21更新
双指针法2
class Solution{
public int[] twoSum(int[] nums, int target){
//新建hashmap
Map<Integer, Integer> map = new HashMap<>();
//循环
for(int i = ;i < nums.length;i++){
int complement = target - nums[i];
//判断当前hashmap中是否有这个减去之后的目标值
if(map.containsKey(complement){
return new int[]{map.get(complement), i};
}
//没有发现则put进下一个键值对
//因为a + b = c,所以先找到a或者先找到b所返回的值是一样的
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two solution");
}
}
2.两数之和
public class ListNode{
int val;
ListNode next;
ListNode(int x){val = x;}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2){
ListNode dummyHead = new ListNode(0);
ListNode p = 1l,q = l2, curr = dummyHead;
int carry = 0;
while(p != null || q != null){
int x = (p!= null)? p.val:0;
int y = (q!= null)? q.val:0;
int sum = carry + x + y;
carry = sum/10;
cur.next = new ListNode(sum);
cur = cur.next;
if(l1 != null){
l1 = l1.nexr;
}
if(l2 != null){
l2 = l2.next;
}
}
if(carry == 1){
cur.next = new ListNode(carry);
}
return pre.next;
}
3.