Algorithm:
給定一個排序數組,你需要在原地删除重複出現的元素,使得每個元素隻出現一次,傳回移除後數組的新
package com.util.main;
import com.tuniu.ngsp.nws.support.util.JsonExceptionUtil;
public class AddTwoNumbers {
public static class ListNode{
private int value;
private ListNode next;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
public ListNode(int value) {
this.value = value;
}
public ListNode(int value,ListNode ln){
this.value=value;
this.next=ln;
}
}
public static ListNode addTwoNumbers(ListNode l1,ListNode l2){
ListNode head = new ListNode(0);
//cur可能認為是一個指針,總是指向末節點的next
ListNode p = l1,q = l2,cur = head;
int carry = 0;
while(p!=null || q!=null){
int x = (p!=null?p.getValue():0);
int y = (q!=null?q.getValue():0);
int sum = carry + x + y;
//進位數
carry = sum/10;
//目前位的和
cur.next = new ListNode(sum%10);
cur = cur.next;
if(p!=null){
p = p.next;
}
if(q!=null){
q = q.next;
}
if(carry>0){
cur.next = new ListNode(carry);
}
}
return head.next;
}
public static void main (String[] args){
ListNode l1a = new ListNode(3);
ListNode l1b = new ListNode(4,l1a);
ListNode l1 = new ListNode(2,l1b);
ListNode l2a = new ListNode(4);
ListNode l2b = new ListNode(6,l2a);
ListNode l2 = new ListNode(5,l2b);
ListNode sum = addTwoNumbers(l1,l2);
System.out.println(JsonExceptionUtil.toString(sum));
}
}
長度。不要使用額外的數組空間,你必須在原地修改輸入數組并在使用O(1)額外空間的條件下完成
示例:
給定 nums = [1,1,2], 函數應該傳回新的長度2,并且原數組nums的前兩個元素被修改為1,2
Review
未能完成
Tips
java8 map新特性
map.getOrDefault 當Map集合中有這個key時,就使用這個key值,如果沒有就使用預設值defaultValue,注意getOrDefault的預設值的生效條件并不是get的值為null,而是containsKey的結果為false,是以如果key擷取的值為null,得到的會是null
Share
如何看英文技術文檔
https://www.jianshu.com/p/af7d39cac6b8