lintcode

2017-9-27

Insert into a Cyclic Sorted List

Given a node from a cyclic linked list which has been sorted, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be any single node in the list. Return the inserted new node.
 
我的
1. node == null 时注意要自建环指向自己。
2.答案有问题??
 1 public class Solution {
 2     /*
 3      * @param node: a list node in the list
 4      * @param x: An integer
 5      * @return: the inserted new list node
 6      */
 7     public ListNode insert(ListNode node, int x) {
 8         // write your code here
 9         if (node == null) {
10             ListNode node1 = new ListNode(x);
11             node1.next = node1;
12             return node1;
13         }
14         ListNode cur = node;
15         ListNode temp = node.next;
16         if (temp.val < x) {
17             cur = cur.next;
18             temp = temp.next;
19         }
20         ListNode newNode = new ListNode(x);
21         cur.next = newNode;
22         newNode.next = temp;
23         return temp;
24     }
25 }
View Code
30->50->2->2->3->5->7->9->11->20
2
50->2->2->2->3->5->7->9->11->20->30
我的错哪里了30->2->50->2->2->3->5->7->9->11->20
想简单了。

kth largest
class Solution {
    public int findKthLargest(int[] nums, int k) {
        if (nums == null) {
            return -1;
        }
        return quickSelect(nums, 0, nums.length, k);
    }
    private int quickSelect(int[] nums, int start, int end, int k) {
        if (start == end) {
            return nums[start];
        }
        int i = start;
        int j = end;
        int pivot = nums[(i + j) / 2];
        while (i <= j) {
            while (i <= j && nums[i] < pivot) {
                i++;
            }
            while (i <= j && nums[j] > pivot) {
                j++;
            }
            if (i <= j) {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
                i++;
                j--;
            }
        }
        if (j >= k)     
    }
}
View Code

 sort list

出现空指针的原因

 while (fast != null && fast.next != null ) {

先写fast 再写fast.next

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param head: The head of linked list.
17      * @return: You should return the head of the sorted linked list, using constant space complexity.
18      */
19     public ListNode sortList(ListNode head) {
20         // write your code here
21         if (head == null || head.next == null) {
22             return head;
23         }
24         ListNode fast = head.next;
25         ListNode slow = head;
26         //ListNode temp = head;
27         while (fast != null && fast.next != null ) {
28           //  temp = slow;
29             fast = fast.next;
30             //if (fast.next == null) {
31             //    break;
32             //}
33             fast = fast.next;
34             slow = slow.next;
35         }
36         ListNode left = head;
37         ListNode right = slow.next;
38         slow.next = null;
39         left = sortList(left);
40         right = sortList(right);
41         return merge(left, right);
42         
43     }
44     private ListNode merge(ListNode l1, ListNode l2) {
45         ListNode dummy = new ListNode(0);
46         ListNode lastNode = dummy;
47         
48         while (l1 != null && l2 != null) {
49             if (l1.val < l2.val) {
50                 lastNode.next = l1;
51                 l1 = l1.next;
52             } else {
53                 lastNode.next = l2;
54                 l2 = l2.next;
55             }
56             lastNode = lastNode.next;
57         }
58         
59         if (l1 != null) {
60             lastNode.next = l1;
61         } else {
62             lastNode.next = l2;
63         }
64         
65         return dummy.next;
66     }
67 }
View Code

mergesort 

merge时使用合并两个有序链表的方法,使用dummy node

 2017-10-22(日)

开始栈

Expression Expand

把重复的元素展开s = abc3[a] return abcaaa

//一个java文件里只能有一个public
class Element {
    String str ;
    int digit;
    public Element (int x) {
        digit = x;
    }
    public Element (String s) {
        str = s;
    }
}
public class Solution {
    /*
     * @param s: an expression includes numbers, letters and brackets
     * @return: a string
     */
    public String expressionExpand(String s) {
        // write your code here
        if (s == null) {
            return s;
        }
        Stack<Element> stack = new Stack<Element>();
        int temp = 0;
        for (char c : s.toCharArray()) {
            //Character.isDigit(c) 不是c.isdigit()!!
            if (Character.isDigit(c)) {
                temp = temp * 10 + c - '0';
            } else if (c == '[') {
                stack.push(new Element(temp));
                temp = 0;
            } else if (Character.isLetter(c)) {
                //不能直接把c放进去 如果new Element(char),那么会把char当int处理。
                stack.push(new Element(String.valueOf(c)));
            } else if (c == ']') {
                String str = getStr(stack);
                int d = stack.pop().digit;
                for (int i = 0; i < d; i++) {
                    stack.push(new Element(str));
                }
            }
        }
        return  getStr(stack);
        
    }
    public String getStr(Stack<Element> stack) {
        Stack<String> tempStack = new Stack<>();
        while ((!stack.isEmpty()) && (stack.peek().str != null)) {
            tempStack.push(stack.pop().str);
        }
        StringBuilder stb = new StringBuilder();
        //String res = "";
        while (!tempStack.isEmpty()) {
            stb.append(tempStack.pop());
            //res+=tempStack.pop();
        }
        return stb.toString();
        //return res;
    }
}
View Code

还可以不用Element类型,使用Object,私以为比较麻烦。

 递归做法,对递归的理解还是不够

 1 public class Solution {
 2     /*
 3      * @param s: an expression includes numbers, letters and brackets
 4      * @return: a string
 5      */
 6     public String expressionExpand(String s) {
 7         // write your code here
 8         int number = 0;
 9         int parent = 0; //此字母之前有没有左括号,父级括号
10         String subString = ""; //在最外层【】之间的值 【subString】
11         StringBuilder sb = new StringBuilder(); //不含【】的最终return的值
12         for (char c : s.toCharArray()) {
13             if (c == '[') {
14                 if (parent > 0) {
15                     subString += c;
16                 }
17                 parent++;
18             } else if (c == ']') {
19                 parent--;
20                 if (parent == 0) {
21                     String expandedString = expressionExpand(subString);
22                     for (int i = 0; i < number; i++) {
23                         sb.append(expandedString);
24                     }
25                     number = 0;
26                     subString = "";
27                 } else {
28                     subString += c;
29                 }
30             } else if (Character.isDigit(c)) {
31                 if (parent == 0) {
32                     number = number * 10 + 'c' - '0';
33                 } else {
34                     subString += c;
35                 }
36             } else {
37                 //letter
38                 if (parent == 0) {
39                     sb.append(String.valueOf(c)); //为什么不能直接append(c);
40                 } else {
41                     subString += c;
42                 }
43             }
44         }
45         return sb.toString();
46         
47     }
48 }
View Code

使用parent记录进入第几层了。

云云的

public class Solution {
    /*
     * @param s: an expression includes numbers, letters and brackets
     * @return: a string
     */
    int index = 0;
    public String expressionExpand(String s) {
        // write your code here
        if (s == null || s.length() == 0) {
            return s;
        }
        char[] ch = s.toCharArray();
        int num = 0;
        StringBuilder res = new StringBuilder(""); 
        for (;index < ch.length; index++) {
            if (Character.isLetter(ch[index])) {
                String temp = String.valueOf(ch[index]);
                res.append(temp);
            } else if (Character.isDigit(ch[index])) {
                num = num * 10 + ch[index] - '0';
            } else if (ch[index] == '[') {
                String str = expand(ch);
                for (int i = 0; i < num; i++) {
                    res.append(str);
                }
                num = 0;
            }
        }
        return res.toString();
    }
    private String expand(char[] ch) {
        StringBuilder res = new StringBuilder("");
        index++;
        int num = 0;
        for (;index < ch.length; index++) {
            if (Character.isLetter(ch[index])) {
                String temp = String.valueOf(ch[index]);
                res.append(temp);
            } else if (Character.isDigit(ch[index])) {
                num = num * 10 + ch[index] - '0';
            } else if (ch[index] == '[') {
                String str = expand(ch);
                for (int i = 0; i < num; i++) {
                    res.append(str);
                }
                num = 0;
            } else if (ch[index] == ']') {
                return res.toString();
            }
        }
        return res.toString();
    }
}
View Code

 

摊平嵌套的列表

 1 /**
 2  * // This is the interface that allows for creating nested lists.
 3  * // You should not implement it, or speculate about its implementation
 4  * public interface NestedInteger {
 5  *
 6  *     // @return true if this NestedInteger holds a single integer,
 7  *     // rather than a nested list.
 8  *     public boolean isInteger();
 9  *
10  *     // @return the single integer that this NestedInteger holds,
11  *     // if it holds a single integer
12  *     // Return null if this NestedInteger holds a nested list
13  *     public Integer getInteger();
14  *
15  *     // @return the nested list that this NestedInteger holds,
16  *     // if it holds a nested list
17  *     // Return null if this NestedInteger holds a single integer
18  *     public List<NestedInteger> getList();
19  * }
20  */
21 import java.util.Iterator;
22 
23 public class NestedIterator implements Iterator<Integer> {
24     private Stack<NestedInteger> stack; //= new Stack<>();
25 
26     public NestedIterator(List<NestedInteger> nestedList) {
27         // Initialize your data structure here.
28         stack = new Stack<>();
29         Stack<NestedInteger> temp = new Stack<>();
30         for (NestedInteger nested : nestedList) {
31             temp.push(nested);
32         }
33         
34         while (!temp.isEmpty()) {
35             stack.push(temp.pop());
36         }
37         //for (int i = stack.size() - 1; i >= 0; i--) {
38         //    stack.push(nestedList.get(i));
39         //}
40     }
41 
42     // @return {int} the next element in the iteration
43     @Override
44     public Integer next() {
45         // Write your code here
46         if (hasNext()) {
47             return stack.pop().getInteger();
48         } else {
49             return null; //??
50         }
51     }
52 
53     // @return {boolean} true if the iteration has more element or false
54     @Override
55     public boolean hasNext() {
56         // Write your code here
57         if (!stack.isEmpty()) {
58            
59             NestedInteger p = stack.peek();
60         
61             if (!p.isInteger()) {
62                 List<NestedInteger> tempList = stack.pop().getList();
63                 Stack<NestedInteger> temp = new Stack<>();
64                 for (NestedInteger nested : tempList) {
65                     temp.push(nested);
66                 }
67         
68                 while (!temp.isEmpty()) {
69                     stack.push(temp.pop());
70                 }
71                 //for (int j = tempList.size() - 1; j >= 0; j--) {
72                 //   stack.push(tempList.get(j));
73                 //}
74                 
75             } 
76                 return true;
77             
78         } else {
79             return false;
80         }
81     }
82 
83     @Override
84     public void remove() {}
85 }
86 
87 /**
88  * Your NestedIterator object will be instantiated and called as such:
89  * NestedIterator i = new NestedIterator(nestedList);
90  * while (i.hasNext()) v.add(i.next());
91  */
View Code

 我的有问题。

 1 /**
 2  * // This is the interface that allows for creating nested lists.
 3  * // You should not implement it, or speculate about its implementation
 4  * public interface NestedInteger {
 5  *
 6  *     // @return true if this NestedInteger holds a single integer,
 7  *     // rather than a nested list.
 8  *     public boolean isInteger();
 9  *
10  *     // @return the single integer that this NestedInteger holds,
11  *     // if it holds a single integer
12  *     // Return null if this NestedInteger holds a nested list
13  *     public Integer getInteger();
14  *
15  *     // @return the nested list that this NestedInteger holds,
16  *     // if it holds a nested list
17  *     // Return null if this NestedInteger holds a single integer
18  *     public List<NestedInteger> getList();
19  * }
20  */
21 import java.util.Iterator;
22 
23 public class NestedIterator implements Iterator<Integer> {
24     Stack<NestedInteger> stack = new Stack<>();
25 
26     public NestedIterator(List<NestedInteger> nestedList) {
27         // Initialize your data structure here.
28         for (int i = nestedList.size() - 1; i >= 0; i--) {
29             stack.push(nestedList.get(i));
30         }
31     }
32 
33     // @return {int} the next element in the iteration
34     @Override
35     public Integer next() {
36         // Write your code here
37         return stack.pop().getInteger();
38     }
39 
40     // @return {boolean} true if the iteration has more element or false
41     @Override
42     public boolean hasNext() {
43         // Write your code here
44         if (stack.isEmpty()) {
45             return false;
46         } else {
47             while (!stack.isEmpty() && !stack.peek().isInteger()) { //[[],[]]->[]
48                 List<NestedInteger> tempList = stack.pop().getList();
49                 for (int j = tempList.size() - 1; j >= 0; j--) {
50                     stack.push(tempList.get(j));
51                 }
52             }
53             return !stack.isEmpty();// 此处要判断,如果【【】,【】】这样,展开后放进去stack为空
54         }
55     }
56 
57     @Override
58     public void remove() {}
59 }
60 
61 /**
62  * Your NestedIterator object will be instantiated and called as such:
63  * NestedIterator i = new NestedIterator(nestedList);
64  * while (i.hasNext()) v.add(i.next());
65  */
View Code

hash函数

1 class Solution {
2     public int hashCode(char[] key,int HASH_SIZE) {
3         long ans = 0;
4         for(int i = 0; i < key.length;i++) {
5             ans = (ans * 33 + (int)(key[i])) % HASH_SIZE; 
6         }
7     return (int)ans;
8     }
9 };
View Code

为什么要用long,为什么要在循环里取模。(分配律)

(a * b) % p = (a % p * b % p) % p 

(a+b) % p = ( a % p + b % p ) % p (9)
((a +b)% p * c) % p = ((a * c) % p + (b * c) % p) % p (10)

 重哈希

 1 /**
 2  * Definition for ListNode
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param hashTable: A list of The first node of linked list
15      * @return: A list of The first node of linked list which have twice size
16      */    
17     public ListNode[] rehashing(ListNode[] hashTable) {
18         // write your code here
19         if (hashTable == null || hashTable.length == 0) {
20             return hashTable;  
21         }
22         int len = hashTable.length;
23         int cpt = len * 2;
24         ListNode[] res = new ListNode[cpt];
25         for (int i = 0; i < len; i++) {
26             ListNode temp = hashTable[i];
27             while (temp != null) {
28                 int pos;
29                 if (temp.val > 0) {
30                      pos = temp.val % cpt;
31                 } else {
32                      pos = (temp.val % cpt + cpt) % cpt;
33                 }
34                 
35                 if (res[pos] == null) {
36                     res[pos] = new ListNode(temp.val);
37                 } else {
38                     ListNode old = res[pos];
39                     //old.next = new ListNode(temp.val);不能这么写,要用while找尾巴
40                     while (old.next != null) {
41                         
42                         old = old.next;
43                     }
44                     old.next = new ListNode(temp.val);
45                 }
46                 temp = temp.next;
47             }
48         }
49         return res;
50     }
51 };
View Code

在添加新ListNode时,注意要找到尾巴。

前K大数

 1 public class Solution {
 2     /*
 3      * @param nums: an integer array
 4      * @param k: An integer
 5      * @return: the top k largest numbers in array
 6      */
 7     public int[] topk(int[] nums, int k) {
 8         // write your code here
 9         int[] res = new int[k];
10         if (nums == null || nums.length == 0) {
11             return res;
12         }
13         int len = nums.length - 1;
14         //造堆
15         for (int i = 0; i < nums.length; i++) {
16             swim(nums, i);
17         }
18         for (int j = 0; j < k; j++) {
19             res[j] = nums[0];
20             int temp = nums[0];
21             nums[0] = nums[len];
22             nums[len] = temp;
23             len = len - 1;
24             sink(nums, len);
25             
26         }
27         return res;
28     }
29     private void sink(int[] nums, int len) {
30         int k = 0;
31         while (2 * k + 1 <= len) {
32             if (2 * k + 2 <= len) {
33                 int t = (nums[2 * k + 1] > nums[2 * k + 2]) ? ( 2 * k + 1) : ( 2 * k + 2);
34                 if (nums[t] <= nums[k]) {
35                     return;
36                 } else {
37                     int temp = nums[t];
38                     nums[t] = nums[k];
39                     nums[k] = temp;
40                     k = t;
41                 }
42             } else {
43                 if (nums[2 * k + 1] > nums[k]) {
44                     int temp = nums[k];
45                     nums[k] = nums[2 * k + 1];
46                     nums[2 * k + 1] = temp;
47                     k = 2 * k + 1;
48                 } else {
49                     return;//忘了!!!
50                 }
51             }
52         }
53         return;
54     }
55     private void swim(int[] nums, int k) {
56         while (k > 0 && nums[(k - 1) / 2] < nums[k]) {
57             int temp = nums[k];
58             nums[k] = nums[(k - 1) / 2];
59             nums[(k - 1) / 2] = temp;
60             k = (k - 1) / 2;
61         }
62     } 
63 }
View Code

注意sink写法。

合并k个排序链表

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */ 
12 public class Solution {
13     /**
14      * @param lists: a list of ListNode
15      * @return: The head of one sorted list.
16      */
17     public ListNode mergeKLists(List<ListNode> lists) {  
18         // write your code here
19         if (lists == null || lists.size() == 0) { //判断!!size() == 0
20             return null;
21         }
22         if (lists.size() == 1) {
23             return lists.get(0);
24         }
25         ListNode merge = mergeTwo(lists.get(0), lists.get(1));
26         
27         
28         for (int i = 2; i < lists.size(); i++) {
29             merge = mergeTwo(merge, lists.get(i));
30         }
31         return merge;
32     }
33     private ListNode mergeTwo(ListNode one, ListNode two) {
34         ListNode i = one;
35         ListNode j = two;
36         ListNode dummy = new ListNode(0);
37         ListNode temp = dummy;
38         while (i != null && j != null) {
39              if (i.val < j.val) {
40                  temp.next = i;
41                  i = i.next;
42              } else {
43                  temp.next = j;
44                  j = j.next;
45              }
46              temp = temp.next;
47         }
48         if (i != null) {
49             temp.next = i;
50         }
51         if (j != null) {
52             temp.next = j;
53         }
54         return dummy.next;
55     }
56 }
View Code

 k个最近的点

 1 /**
 2  * Definition for a point.
 3  * class Point {
 4  *     int x;
 5  *     int y;
 6  *     Point() { x = 0; y = 0; }
 7  *     Point(int a, int b) { x = a; y = b; }
 8  * }
 9  */
10 
11 
12 public class Solution {
13     /*
14      * @param points: a list of points
15      * @param origin: a point
16      * @param k: An integer
17      * @return: the k closest points
18      */
19     public Point[] kClosest(Point[] points, Point origin, int k) {
20         // write your code here
21         
22         if (points == null || points.length < k) { //不知道怎么判断
23             return points;
24         } 
25         Arrays.sort(points, new Comparator<Point>() {
26             public int compare(Point a, Point b) {
27                 int lena = (a.x - origin.x) * (a.x - origin.x) + (a.y - origin.y) * (a.y - origin.y);
28                 int lenb = (b.x - origin.x) * (b.x - origin.x) + (b.y - origin.y) * (b.y - origin.y);
29                 if (lena == lenb) { //lena == lenb
30                     if (a.x > b.x) {
31                         return 1;
32                     } else if (a.x < b.x) {
33                         return -1;
34                     } else {
35                         return a.y - b.y;
36                     }
37                 } else {
38                     return lena - lenb;
39                 }
40             }
41         });
42         Point[] res = new Point[k];
43         for (int i = 0; i < k; i++) {
44             res[i] = points[i];
45         }
46         return res;
47     }
48 }
View Code

 优先队列PQ比较器写法。

如果不提供Comparator的话,优先队列中元素默认按自然顺序排列,也就是数字默认是小的在队列头。比如队列 1 3 5 10 2 自动会被排列 1 2 3 5 10

1 cmp = new Comparator<Integer>() { 
2             public int compare(Integer e1, Integer e2) {
3                 return e2 - e1;
4             }
5         };
6 Queue<Integer> q2 = new PriorityQueue<Integer>(5, cmp);

PriorityQueue(int initialCapacity, Comparator<? super E> comparator)

Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.
只有这样初始化的时候加入比较器,但是必须有大小?
 
LRU缓存策略
 1 class Node { //double list node
 2     public int v;
 3     public int k;
 4     public Node pre;
 5     public Node next;
 6     public Node(int a, int b) {
 7         v = b;
 8         k = a;
 9         pre = null;
10         next = null;
11     }
12 }
13 public class LRUCache {
14     /*
15     * @param capacity: An integer
16     */
17     private Map<Integer, Node> map = new HashMap<>();
18     private int c; //缓存容量
19     private Node head = new Node(-1, -1);
20     private Node tail = new Node(-1, -1);
21     public LRUCache(int capacity) {
22         // do intialization if necessary
23         c = capacity;
24         head.next = tail;
25         tail.pre = head;
26     }
27 
28     /*
29      * @param key: An integer
30      * @return: An integer
31      */
32     public int get(int key) {
33         // write your code here
34         if (!map.containsKey(key)) {
35             return -1;
36         } else { 
37             //如果key在缓存map中,则把它移到尾巴上。
38             Node temp = map.get(key);
39             int res = temp.v;
40             Node left = temp.pre;
41             Node right = temp.next;
42             left.next = right;
43             right.pre = left;
44             temp.pre = tail.pre;
45             tail.pre.next = temp;
46             tail.pre = temp;
47             temp.next = tail;
48             return res;
49         }
50     }
51 
52     /*
53      * @param key: An integer
54      * @param value: An integer
55      * @return: nothing
56      */
57     public void set(int key, int value) {
58         // write your code here
59         if (map.containsKey(key)) {
60             //放到尾巴,并且重置值value
61             get(key);
62             map.get(key).v = value;
63             
64         } else {
65             //不含key,分情况 是否达到上限
66             if (map.size() < c) {
67                 //没放满,放在尾巴
68                 Node add = new Node(key, value);
69                 map.put(key, add);
70                 tail.pre.next = add;
71                 add.pre = tail.pre;
72                 add.next = tail;
73                 tail.pre = add;
74             } else {
75                 //放满了,删除
76                 Node delete = head.next;
77                 map.remove(delete.k);
78                 head.next = delete.next;
79                 delete.next.pre = head;
80                 //加入新的
81                 Node zhu = new Node(key, value);
82                 map.put(key, zhu);
83                 tail.pre.next = zhu;
84                 zhu.pre = tail.pre;
85                 zhu.next = tail;
86                 tail.pre = zhu;
87                 
88             }
89         }
90     }
91     
92 }
View Code

 等于是自己实现一个LinkedHashMap

 strStr
 1 public class Solution {
 2     /*
 3      * @param source: A source string
 4      * @param target: A target string
 5      * @return: An integer as index
 6      */
 7     public int strStr2(String source, String target) {
 8         // write your code here
 9         if (source == null || target == null) {
10             return -1;
11         }
12         if (target.length() == 0) {
13             return 0;
14         }
15         int base = 1000000;
16         int m = target.length();
17         //31^m
18         int power = 1;
19         for (int i = 0; i < m; i++) {
20             power = (power * 31) % base;
21         }
22         int thash = 0;
23         for (int i = 0; i < m; i++) {
24             thash = (thash * 31 + target.charAt(i)) % base;
25         }
26         int shash = 0;
27         for (int i = 0; i < source.length(); i++) {
28             shash = (shash * 31 + source.charAt(i)) % base;
29             
30             if (i < m - 1) {
31                 continue;
32             }
33             
34             if (i >= m) {
35                 shash = shash - source.charAt(i - m) * power % base;
36             }
37             if (shash < 0) {
38                 shash = (shash + base) % base;                                
39             } else {
40                 shash = shash % base;
41             }
42             
43             if (shash == thash) {
44                 if (source.substring(i - m + 1, i + 1).equals(target)) {
45                     return i - m + 1;
46                 }
47             }
48         }
49         return -1;
50     }
51 }
View Code

dp

注意判断边界,obstacle【0】【0】 == 1,这样不用进行计算了,直接return 0;

 1 public class Solution {
 2     /*
 3      * @param obstacleGrid: A list of lists of integers
 4      * @return: An integer
 5      */
 6     public int uniquePathsWithObstacles(int[][] obstacleGrid) {
 7         // write your code here
 8         if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0 || obstacleGrid[0][0] == 1) {
 9             return 0;
10         }
11         //obstacle: 1
12         int m = obstacleGrid.length;
13         int n = obstacleGrid[0].length;
14         int[][] f = new int[m][n];
15         //initialize!!!
16         //如果obstacleGrid[0][0] 为1,则直接return 0;
17         f[0][0] = 1;
18         for (int i = 1; i < m; i++) {
19             if (obstacleGrid[i][0] == 1) {
20                 f[i][0] = 0;
21             } else {
22                 f[i][0] = f[i - 1][0];
23             }
24         }
25         for (int j = 1; j < n; j++) {
26             if (obstacleGrid[0][j] == 1) {
27                 f[0][j] = 0;
28             } else {
29                 f[0][j] = f[0][j - 1];
30             }
31         }
32         for (int i = 1; i < m; i++) {
33             for (int j = 1; j < n; j++) {
34                 if (obstacleGrid[i][j] == 0) {
35                     f[i][j] = f[i - 1][j] + f[i][j - 1];
36                 } else {
37                     f[i][j] = 0;
38                 }
39             }
40         }
41         return f[m - 1][n - 1];
42     }
43 }
View Code

 跳跃游戏

 1 public class Solution {
 2     /*
 3      * @param A: A list of integers
 4      * @return: A boolean
 5      */
 6     public boolean canJump(int[] A) {
 7         // write your code here
 8         if (A == null || A.length == 0) {
 9             return true;
10         }
11         int[] f = new int[A.length];
12         f[0] = 1;
13         for (int i = 1; i < A.length; i++) {
14             f[i] = 0;
15         }
16         for (int i = 0; i < A.length - 1; i++) { //不用考虑最后一个位置跳多远
17             int steps = A[i];
18             if (f[i] == 1) {
19                 for (int j = 1; j <= steps; j++) {
20                     if (i + j <= A.length - 1)  {
21                         f[i + j] = 1;
22                     }//可跳跃最大长度可能越界
23                         
24                 }
25                     
26             } else{
27                 return false;
28             }
29         }
30             
31         
32         if (f[A.length - 1] == 1) {
33             return true;
34         } 
35         return false;
36     }
37 }
View Code

o(n)的做法,不知道算不算贪心

 1 public class Solution {
 2     /*
 3      * @param A: A list of integers
 4      * @return: A boolean
 5      */
 6     public boolean canJump(int[] A) {
 7         // write your code here
 8         if (A == null || A.length == 0) {
 9             return true;
10         }
11         int steps = A[0];
12         for (int i = 1; i < A.length - 1; i++) { //考虑【1,0】情况
13             steps--;
14             if (steps <= 0) {
15                 return false;
16             } else if (A[i] > steps) {
17                 int temp = A[i];
18                 A[i] = steps;
19                 steps = temp;
20             }
21         }
22         return true;
23     }
24 }
View Code

 完美平方:两层循环都写不出来!!!

 1 public class Solution {
 2     /*
 3      * @param n: a positive integer
 4      * @return: An integer
 5      */
 6     public int numSquares(int n) {
 7         // write your code here
 8         //完全平方数 1 2 3 4 5 -> 1 4 9 16 25
 9         int[] f = new int[n + 1];
10         f[0] = 0;
11         f[1] = 1;
12         for (int i = 1; i <= n; i++) {
13             f[i] = Integer.MAX_VALUE;
14             for (int j = 1; j * j <= i; j++) { //脑子坏掉了
15                 if (1 + f[i - j * j] < f[i]) {
16                     //f[j*j] = 1
17                     f[i] = 1 + f[i - j * j];
18                 }
19             }
20         }
21         return f[n];
22     }
23 }
View Code

 drop eggs

 1 public class Solution {
 2     /*
 3      * @param n: An integer
 4      * @return: The sum of a and b
 5      */
 6     public int dropEggs(int n) {
 7         // write your code here
 8         long k = 0;
 9         long i = 0;
10         while (k < n) {
11             i++;
12             k += i;
13             
14         }
15         return (int)i;
16         //10层
17         //1 2 3 4√ 5 6 7√ 8 9√ 10
18         //10 - 1 = 9
19         //9 - 2 = 7
20         //7 - 3 = 4
21         //4 - 4 = 0
22     }
23 }
View Code

第一次最高可以在第x层尝试丢。易知第二次最高可以在第x + x - 1层丢,因为若之前在第x层丢的没有碎则应继续往高层找,而此时已经消耗了一次丢鸡蛋的机会,所以只能往上再增加x - 1层。
依次可知, x + (x - 1) + (x - 2) + ... + 2 + 1 >= 100, 求出x最小值是14。

http://datagenetics.com/blog/july22012/index.html

drop eggs ii

动态规划+递归。用二元数组存储某鸡蛋某层所需的次数。迭代试扔第一个鸡蛋,在某层扔。1.扔碎了即转为鸡蛋少一个,楼层少一层的子问题。2.没扔碎即转化为鸡蛋没有少楼层少为上半层那么多的子问题。

 两个整数相除

 1 public class Solution {
 2     /*
 3      * @param dividend: the dividend
 4      * @param divisor: the divisor
 5      * @return: the result
 6      */
 7     public int divide(int dividend, int divisor) {
 8         // write your code here
 9         if (divisor == 0) {
10              return dividend >= 0? Integer.MAX_VALUE : Integer.MIN_VALUE;
11         }
12         boolean isNegative = (dividend < 0 && divisor > 0) || 
13                              (dividend > 0 && divisor < 0);
14         if (dividend == Integer.MIN_VALUE && divisor == -1) {
15             return Integer.MAX_VALUE;
16         }                     
17         int res =  div(Math.abs((long)dividend), Math.abs((long)divisor));
18         if (isNegative) {
19             return -res;
20         } else {
21             return res;
22         }
23         
24     }
25     public int div(long dividend, long divisor) {
26          if (dividend < divisor) {
27             return 0;
28         }
29         long pre = divisor;
30         long cur = divisor + divisor;
31         int i = 1;
32         while (cur <= dividend) {
33             pre = cur;
34             cur = cur + cur;
35             i = i + i;
36         }
37         return div(dividend - pre, divisor) + i;
38     }
39 }
View Code

 

 1 public class Solution {
 2     /**
 3      * @param dividend the dividend
 4      * @param divisor the divisor
 5      * @return the result
 6      */
 7     public int divide(int dividend, int divisor) {
 8         if (divisor == 0) {
 9              return dividend >= 0? Integer.MAX_VALUE : Integer.MIN_VALUE;
10         }
11         
12         if (dividend == 0) {
13             return 0;
14         }
15         
16         if (dividend == Integer.MIN_VALUE && divisor == -1) {
17             return Integer.MAX_VALUE;
18         }
19         
20         boolean isNegative = (dividend < 0 && divisor > 0) || 
21                              (dividend > 0 && divisor < 0);
22                              
23         long a = Math.abs((long)dividend);
24         long b = Math.abs((long)divisor);
25         int result = 0;
26         while(a >= b){
27             int shift = 0;
28             while(a >= (b << shift)){
29                 shift++;
30             }
31             a -= b << (shift - 1);
32             result += 1 << (shift - 1);
33         }
34         return isNegative? -result: result;
35     }
36 }
View Code

 596

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param root: the root of binary tree
     * @return: the root of the minimum subtree
     */
     class Type {
         TreeNode minNode = null;
         int sum = 0;
         int minSum = Integer.MAX_VALUE;
         Type(TreeNode t, int s, int m) {
             minSum = m;
             sum = s;
             minNode = t;
         }
     }
    public TreeNode findSubtree(TreeNode root) {
        // write your code here
        Type t = curCon(root);
        return t.minNode;
    }
    //
    private Type curCon(TreeNode root) {
        if (root == null) {
            return new Type(root, 0, Integer.MAX_VALUE);
        }
        //pan duan yezi
        
        Type left = curCon(root.left);
        Type right = curCon(root.right);
        int sum = left.sum + right.sum + root.val;
        TreeNode temp = root;
        int minSum = sum;
        
        if (right.minSum < minSum) {
            temp = right.minNode;
            minSum = right.minSum;
            
        }
        if (minSum > left.minSum) {
             temp = left.minNode;
             minSum = left.minSum;
        }
        
        return new Type(temp, sum, minSum);
        
    }
}
View Code

 

posted @ 2017-09-27 19:13  yunyouhua  阅读(446)  评论(0编辑  收藏  举报