Two Sum 和 Add Two Numbers 12月16日
Two Sum
最简单的方法就是遍历,难度o(n^2)
另外可以用HashMap,把i和nums[i]存进map里。复杂度O(n)。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res= new int[2];
if(nums==null||nums.length==0){
return null;
}
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
res[1]=i;
res[0]=map.get(temp);
}
map.put(nums[i],i);
}
return res;
}
}
Add Two Numbers
/**
* 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) {
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
ListNode head = new ListNode(0);
ListNode node=new ListNode(0);
int add=0;
node=head;
while(l1!=null||l2!=null){
if(l1!=null&&l2!=null){
ListNode node2=new ListNode((l1.val+l2.val+add)%10);
add=(l1.val+l2.val+add)/10;
node.next=node2;
node=node2;
l1=l1.next;
l2=l2.next;
}
else if(l1!=null){
ListNode node2=new ListNode((l1.val+add)%10);
node.next=node2;
node=node2;
add=(l1.val+add)/10;
l1=l1.next;
}
else if(l2!=null){
ListNode node3=new ListNode((l2.val+add)%10);
node.next=node3;
node=node3;
add=(l2.val+add)/10;
l2=l2.next;
}
}
if(add!=0){
ListNode node2=new ListNode(add);
node.next=node2;
}
return head.next;
}
}
我出错的地方是
ListNode node2=new ListNode((l1.val+l2.val+add)%10);
node.next=node2;
node=node2;
不能直接对node.next赋值。因为node.next是null,没有分配空间。会出现java.lang.NullPointerException