zoukankan      html  css  js  c++  java
  • LintCode 1-30;

    Difficulty--Naive

    463.Sort Integer  整数排序:http://www.lintcode.com/en/problem/sort-integers/#

    冒泡排序:(两两比较取出最大的放最后)

    (外循环-趟数0,n-1;内循环-有序区的比较次数n-i-1趟;判断a[j] a[j+1])

     1 public class Solution {
     2     /**
     3      * @param A an integer array
     4      * @return void
     5      */
     6     public void sortIntegers(int[] a) {
     7         // Write your code here
     8         int tmp = 0;
     9         int size = a.length;
    10         for (int i = 0; i < size - 1; i++) {
    11             for (int j = 0; j < size - i - 1; j++){
    12                 if (a[j] > a[j + 1]) {
    13                     tmp = a[j];
    14                     a[j] = a[j + 1];
    15                     a[j + 1] = tmp;
    16                 }
    17             }
    18         }
    19     }
    20 }
    View Code

    选择排序:(一趟:从无序区中找到最小的数放到有序区的末尾)

    (外循环i 0,n-1;内循环为j=i+1,n; 判断a[i] a[j])

     1 public class Solution {
     2     /**
     3      * @param A an integer array
     4      * @return void
     5      */
     6     public void sortIntegers(int[] a) {
     7         // Write your code here
     8         int tmp = 0;
     9         int size = a.length;
    10         for (int i = 0; i < size - 1; i++) {
    11             for (int j = i + 1; j < size; j++){
    12                 if (a[i] > a[j]) {
    13                     tmp = a[j];
    14                     a[j] = a[i];
    15                     a[i] = tmp;
    16                 }
    17             }
    18         }
    19     }
    20 }
    View Code

    插入排序:(一次:从无序区中的第一位与有序区序列中从后向前扫描;大于target则向后移,小于则插入该位置)

    (外循环i:1-n; tar=a[i]; 内循环j=i,j>0&&tar<a[j-1],j--;  a[j]=a[j-1] ; 循环外a[j]=tar;)

     1 public class Solution {
     2     /**
     3      * @param A an integer array
     4      * @return void
     5      */
     6     public void sortIntegers(int[] a) {
     7         // Write your code here
     8         int size = a.length;
     9         int j;
    10         for (int i = 1; i < size; i++) {
    11             int tar = a[i];
    12             for (j = i; j > 0 && tar < a[j - 1]; j--) {
    13                 a[j] = a[j - 1];
    14             }
    15             a[j] = tar;
    16         }
    17     }
    18 }
    View Code

    366.Fibonacci:http://www.lintcode.com/en/problem/fibonacci/

    我的解法:数组(考虑到数组个数的固定,需要讨论0,1情况)

     1 class Solution {
     2     /**
     3      * @param n: an integer
     4      * @return an integer f(n)
     5      */
     6     public int fibonacci(int n) {
     7         // write your code here
     8         int[] array = new int[n];
     9         array[0] = 0;
    10         if (n > 1){
    11             array[1] = 1;
    12             if (n > 2) {
    13                 for (int i = 2; i < n; i++) {
    14                     array[i] = array[i - 1] + array[i - 2];
    15                 }
    16             }
    17         }
    18         return array[n - 1];
    19     }
    20 }
    View Code

    九章:赋值 移动 

    (a,b, for(0,n-1)c=a+b,a,b return a) (n=1时不执行循环,n=2时执行循环,先求出两数之和作为下一位数,再将a,b分别后移一位)

     1 class Solution {
     2     /**
     3      * @param n: an integer
     4      * @return an integer f(n)
     5      */
     6     public int fibonacci(int n) {
     7         int a = 0;
     8         int b = 1;
     9         for (int i = 0; i < n - 1; i++) {
    10             int c = a + b;
    11             a = b;
    12             b = c;
    13         }
    14         return a;
    15     }
    16 }
    View Code

    452.Remove Linked List Elements:http://www.lintcode.com/en/problem/remove-linked-list-elements/

    从链表中删除元素:(dummy为head的前指针;dummy.next=head; head=dummy 相当于dummy成为新的head,是静态的;然后head开始向后移动;这样整个链表就没有特殊节点了,所有节点都有前指针) [while(!=null) 判断(.val = val; .next=.next.next) else (head = head.next) return dummy.next]

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     /**
    11      * @param head a ListNode
    12      * @param val an integer
    13      * @return a ListNode
    14      */
    15     public ListNode removeElements(ListNode head, int val) {
    16         // Write your code here
    17         ListNode dummy = new ListNode(0);
    18         dummy.next = head;
    19         head = dummy;
    20         while (head.next != null) {
    21             if (head.next.val == val){
    22                 head.next = head.next.next;
    23             } else {
    24                 head = head.next;
    25             }
    26         }
    27         return dummy.next;
    28     }
    29 }
    View Code

    Difficulty--Easy/Medium

    1.A+B Problem:http://www.lintcode.com/en/problem/a-b-problem/#

    A+B:(x=x^y, y=(x&y)<<1)

    位运算实现整数加法本质就是用二进制进行运算。其主要用了两个基本表达式:

    x^y //执行加法,不考虑进位。
    (x&y)<<1 //进位操作
    令x=x^y ;y=(x&y)<<1 进行迭代,每迭代一次进位操作右面就多一位0,最多需要“加数二进制位长度”次迭代就没有进位了,此时x^y的值就是结果。

    我们来做个3位数的加法:
    101+011=1000 //正常加法
    位运算加法:
    (1) 101 ^ 011 = 110
    (101 & 011)<<1 = 010
    (2) 110 ^ 010 = 100
    (110 & 010)<<1 = 100
    (3) 100 ^ 100 = 000
    (100 & 100)<<1 = 1000
    此时进行相加操作就没有进位了,即000 ^ 1000=1000即是最后结果。

    class Solution {
        /*
         * param a: The first integer
         * param b: The second integer
         * return: The sum of a and b
         */
        public int aplusb(int a, int b) {
            while(b != 0){
                int carry = a & b;
                a = a ^ b;
                b = carry << 1;
            }
            return a;
        }
    }
    View Code
     1 class Solution {
     2     /*
     3      * param a: The first integer
     4      * param b: The second integer
     5      * return: The sum of a and b
     6      */
     7     public int aplusb(int a, int b) {
     8         // write your code here, try to do it without arithmetic operators.
     9         if (b == 0) {
    10             return a;
    11         }
    12         int sum = a ^ b;
    13         int carry = (a & b) << 1;
    14         return aplusb(sum, carry);
    15     }
    16 };
    View Code

    2.Trailing Zeros:http://www.lintcode.com/en/problem/trailing-zeros/

    求n!尾零的个数:(n!尾零=n!中质因子5的个数=floor(n/5)+floor(n/25)+……)

    (while(n!=0) sum+=n/5;n=n/5)

     1 class Solution {
     2     /*
     3      * param n: As desciption
     4      * return: An integer, denote the number of trailing zeros in n!
     5      */
     6     public long trailingZeros(long n) {
     7         // write your code here
     8         long sum = 0;
     9         while (n != 0) {
    10             sum += n / 5;
    11             n /= 5;
    12         }
    13         return sum;
    14     }
    15 };
    View Code

    3.Digit Counts:http://www.lintcode.com/en/problem/digit-counts/

    计算0-n中含有数字k的个数:(先求出单个数i含有k的个数--(考虑特殊i=0;k=0) while(i!=0)i%10=k,cnt++;i=i/10;  digitCounts=[k,n]求和singleCount)

    (singleCount if;while-if(余数)cnt++;i/10;  digitCounts=[k,n]singCount)

     1 class Solution {
     2     /*
     3      * param k : As description.
     4      * param n : As description.
     5      * return: An integer denote the count of digit k in 1..n
     6      */
     7     public int digitCounts(int k, int n) {
     8         // write your code here
     9         int cnt = 0;
    10         for (int i = k; i <= n; i++) {
    11             cnt += singleCount(i, k);
    12         }
    13         return cnt;
    14     }
    15     public int singleCount(int i, int k) {
    16         if (i == 0 && k == 0){
    17             return 1;
    18         }
    19         int cnt = 0;
    20         while (i > 0){
    21             if (i % 10 == k) {
    22                 cnt++;
    23             }
    24             i /= 10;
    25         }
    26         return cnt;
    27     }
    28 };
    View Code

    4.Ugly Number II:http://www.lintcode.com/en/problem/ugly-number-ii/

    求第n个丑数(只含2.3.5因子):(new ArrayList, uglys.add(1),定义3个指针p2/p3/p5,分别代表指向3个数组中已添加的位置;和uglys的LastNumber比较,<=则指针后移一位;取3个数组所指的min作为uglys.add;注意get(p)指向的是已经添加到uglys中的数;所以代码中用到的都需要是get(p)*2/3/5)

    (ArrayList<Integer>(); add(1); for(1-n) lastNumber,while(<=)p++; add(Math.min(Math.min)))

    1-n的丑数:1,2,3,4,5,6,8,9,10,12,15…… 可以分为如下3组:

    (1)1, 1×2, 2×2, 3×2, 4×2, 5×2, 6×2, 8×2, …
    (2)1, 1×3, 2×3, 3×3, 4×3, 5×3, 6×3, 8×3, …
    (3)1, 1×5, 2×5, 3×5, 4×5, 5×5, 6×5, 8×5, … 

    只需每次添加的数为3组中最小的值

     1 class Solution {
     2     /**
     3      * @param n an integer
     4      * @return the nth prime number as description.
     5      */
     6     public int nthUglyNumber(int n) {
     7         List<Integer> uglys = new ArrayList<Integer>();
     8         uglys.add(1);
     9         int p2 = 0, p3 = 0, p5 = 0;
    10         // p2, p3 & p5 share the same queue: uglys
    11         for (int i = 1; i < n; i++) {
    12             int lastNumber = uglys.get(i - 1);
    13             while (uglys.get(p2) * 2 <= lastNumber) p2++;
    14             while (uglys.get(p3) * 3 <= lastNumber) p3++;
    15             while (uglys.get(p5) * 5 <= lastNumber) p5++;
    16             uglys.add(Math.min(
    17                 Math.min(uglys.get(p2) * 2, uglys.get(p3) * 3),
    18                 uglys.get(p5) * 5
    19             ));
    20         }
    21         return uglys.get(n - 1);
    22     }
    23 };
    View Code

    5.Kth Largest Element:http://www.lintcode.com/en/problem/kth-largest-element/

    第K大的数

    LeetCode discuss:https://discuss.leetcode.com/category/223/kth-largest-element-in-an-array

    (to do)

     Arrays.sort -- O(nlgn);

     1 class Solution {
     2     /*
     3      * @param k : description of k
     4      * @param nums : array of nums
     5      * @return: description of return
     6      */
     7     public int kthLargestElement(int k, int[] nums) {
     8         // write your code here
     9         Arrays.sort(nums);
    10         return nums[nums.length-k];
    11     }
    12 };
    View Code

    6.Merge Two Sorted Arrays:http://www.lintcode.com/en/problem/merge-two-sorted-arrays/

    合并两个已排数组:(C=[A+B];插入排序思想,A为有序区,B为无序区;)

    (for1:c[i]=a[i];  for2:c[i]=b[i-al],tar;  for2.1: j=i,c[j-1]>tar,j-- ; c[j]=tar)

     1 class Solution {
     2     /**
     3      * @param A and B: sorted integer array A and B.
     4      * @return: A new sorted integer array
     5      */
     6     public int[] mergeSortedArray(int[] A, int[] B) {
     7         // Write your code here
     8         int al = A.length;
     9         int bl = B.length;
    10         int[] C = new int[al + bl];
    11         for (int i = 0; i < al; i++) {
    12             C[i] = A[i];
    13         }
    14         for (int i = al; i < al + bl; i++) {
    15             C[i] = B[i - al];
    16             int tar = C[i];
    17             int j;
    18             for (j = i; j > 0 && C[j - 1] > tar; j--){
    19                 C[j] = C[j - 1];
    20             }
    21             C[j] = tar;
    22         }
    23         return C;
    24     }
    25 }
    View Code

    7.Binary Tree Serialization:http://www.lintcode.com/en/problem/binary-tree-serialization/

    二叉树的序列化和反序列化:(to do)

    8.Rotate-String:http://www.lintcode.com/en/problem/rotate-string/

    根据给定偏移量旋转字符串:

    9.Fizz Buzz:http://www.lintcode.com/en/problem/fizz-buzz/

    打印1-n,其中整除3的用Fizz代替,整除5的用Buzz代替,整除15的用Fizz Buzz代替;

    (ArrayList; 15放在第一个判断;add ; else if; else(String.valueOf(i)));

     1 class Solution {
     2     /**
     3      * param n: As description.
     4      * return: A list of strings.
     5      */
     6     public ArrayList<String> fizzBuzz(int n) {
     7         ArrayList<String> results = new ArrayList<String>();
     8         for (int i = 1; i <= n; i++) {
     9             if (i % 15 == 0) {
    10                 results.add("fizz buzz");
    11             } else if (i % 5 == 0) {
    12                 results.add("buzz");
    13             } else if (i % 3 == 0) {
    14                 results.add("fizz");
    15             } else {
    16                 results.add(String.valueOf(i));
    17             }
    18         }
    19         return results;
    20     }
    21 }
    View Code

    11. Search Range in Binary Search Tree:http://www.lintcode.com/en/problem/search-range-in-binary-search-tree/

    找出给定范围的二叉树中的值:(遍历和递归思想;root>k1 那么要递归遍历左树(找出所有大于k1的); k1<=root<=k2,add; root>k2,递归遍历右树)

    (result; helper; >k1,k1<=root<=k2,<k2;)

     1 public class Solution {
     2     private ArrayList<Integer> results;
     3     /**
     4      * @param root: The root of the binary search tree.
     5      * @param k1 and k2: range k1 to k2.
     6      * @return: Return all keys that k1<=key<=k2 in increasing order.
     7      */
     8     public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
     9         results = new ArrayList<Integer>();
    10         helper(root, k1, k2);
    11         return results;
    12     }
    13     
    14     private void helper(TreeNode root, int k1, int k2) {
    15         if (root == null) {
    16             return;
    17         }
    18         if (root.val > k1) {
    19             helper(root.left, k1, k2);
    20         }
    21         if (root.val >= k1 && root.val <= k2) {
    22             results.add(root.val);
    23         }
    24         if (root.val < k2) {
    25             helper(root.right, k1, k2);
    26         }
    27     }
    28 }
    View Code

    12.Min Stack:http://www.lintcode.com/en/problem/min-stack/

    实现栈minStack的push,pop,min功能;要求时间复杂度均为O(1):(建立两个栈分别为stack和minStack,其中stack正常push和pop,而minStack只push进min值,注意:两个栈的大小始终相同!)

    (push: stack.push; if(empty) else push min(num,peek);  pop:minStack.pop,return stack.pop;  min:return minStack.peek)

    Java Stack类:isEmpty(),peek()查看顶部对象,pop()移除顶部对象并作为返回值返回该对象,push()压入顶部;

     1 public class MinStack {
     2     private Stack<Integer> stack;
     3     private Stack<Integer> minStack;
     4     
     5     public MinStack() {
     6         stack = new Stack<Integer>();
     7         minStack = new Stack<Integer>();
     8     }
     9 
    10     public void push(int number) {
    11         stack.push(number);
    12         if (minStack.isEmpty()) {
    13             minStack.push(number);
    14         } else {
    15             minStack.push(Math.min(number, minStack.peek()));
    16         }
    17     }
    18 
    19     public int pop() {
    20         minStack.pop();
    21         return stack.pop();
    22     }
    23 
    24     public int min() {
    25         return minStack.peek();
    26     }
    27 }
    View Code

    13.strStr:http://www.lintcode.com/en/problem/strstr/

    匹配字符串:(外循环i(0,sl-tl-1); 内循环j(0,tl); if(!=),break; if(j=tar)return i;)

    ps:数组array.length属性;字符串String.length()方法;String.charAt(i);

    注意:1.String.length()括号; 2.if(==)判断语句,不要漏写=; 3.for循环条件不要漏+1

     1 class Solution {
     2     /**
     3      * Returns a index to the first occurrence of target in source,
     4      * or -1  if target is not part of source.
     5      * @param source string to be scanned.
     6      * @param target string containing the sequence of characters to match.
     7      */
     8     public int strStr(String source, String target) {
     9         if (source == null || target == null) {
    10             return -1;
    11         }
    12         
    13         for (int i = 0; i < source.length() - target.length() + 1; i++) {
    14             int j = 0;
    15             for (j = 0; j < target.length(); j++) {
    16                 if (source.charAt(i + j) != target.charAt(j)) {
    17                     break;
    18                 }
    19             }
    20             // finished loop, target found
    21             if (j == target.length()) {
    22                 return i;
    23             }
    24         }
    25         return -1;
    26     }
    27 }
    View Code

    14.First Position of Target:http://www.lintcode.com/en/problem/first-position-of-target/

    O(logn)查找第一个目标数--二分查找:

    [ while判断 start+1<end(表示之间至少有一个数);  mid=start+()/2 ;

    if(=tar)end=mid(要找出first 为了防重复需要mid=end继续查找左半查找);  if(<tar)start; if(>tar)end;

    if(nums[start]=tar)return start;if()return end; (start)要放在前面判断;]

     1 class Solution {
     2     /**
     3      * @param nums: The integer array.
     4      * @param target: Target to find.
     5      * @return: The first position of target. Position starts from 0.
     6      */
     7     public int binarySearch(int[] nums, int target) {
     8         if (nums == null || nums.length == 0) {
     9             return -1;
    10         }
    11         
    12         int start = 0, end = nums.length - 1;
    13         while (start + 1 < end) {
    14             int mid = start + (end - start) / 2;
    15             if (nums[mid] == target) {
    16                 end = mid;
    17             } else if (nums[mid] < target) {
    18                 start = mid;
    19                 // or start = mid + 1
    20             } else {
    21                 end = mid;
    22                 // or end = mid - 1
    23             }
    24         }
    25         
    26         if (nums[start] == target) {
    27             return start;
    28         }
    29         if (nums[end] == target) {
    30             return end;
    31         }
    32         return -1;
    33     }
    34 }
    View Code

    2016.12.9

    15.Permutations:http://www.lintcode.com/en/problem/permutations/

    返回给定数组的全排列: 

    (helper(rst,list,num):判断if(size()=length)add,return; for()if(contain->continue)add,helper,remove;    permute:1.nul;l 2.length==0;  new list,helper,return rst;)

    个人对代码流程的理解:

    (for循环i=0;add num[0];递归helper()到(执行for i=0continue i=1add)[1,2]继续递归;remove,执行for(i=2)[1,3])->remove->for循环i=1;

    From LeetCode Discuss;

    To generate all possible permutations, we need to remove the least recently added element while we are going up the recursive call stack.
    In the first iteration of the for loop we add all permutations, that start with nums[0]. Then, before we can begin building all permutations starting with nums[1], we need to clear the tempList (which currently contains permutations from the first iteration of the for loop) - that's exactly what tempList.remove(tempList.size() - 1) line does.

     1 public class Solution {
     2     public List<List<Integer>> permute(int[] nums) {
     3          ArrayList<List<Integer>> rst = new ArrayList<List<Integer>>();
     4          if (nums == null) {
     5              return rst; 
     6          }
     7          
     8          if (nums.length == 0) {
     9             rst.add(new ArrayList<Integer>());
    10             return rst;
    11          }
    12 
    13          ArrayList<Integer> list = new ArrayList<Integer>();
    14          helper(rst, list, nums);
    15          return rst;
    16     }
    17     
    18     public void helper(ArrayList<List<Integer>> rst, ArrayList<Integer> list, int[] nums){
    19         if(list.size() == nums.length) {
    20             rst.add(new ArrayList<Integer>(list));
    21             return;
    22         }
    23         
    24         for(int i = 0; i < nums.length; i++){
    25             if(list.contains(nums[i])){
    26                 continue;
    27             }
    28             list.add(nums[i]);
    29             helper(rst, list, nums);
    30             list.remove(list.size() - 1);
    31         }
    32         
    33     }
    34 }
    View Code

    16.Permutations II:http://www.lintcode.com/en/problem/permutations-ii/

     含重复数组的全排列:(利用visited做标记,判断语句使得重复部分的数字顺序和结果中的顺序相同;)

    (helper(rst,list,visited,nums); if(size=length)add,return;  for()if(v=1||i!=0&[i]=[i-1]&v[i-1]=0)continue,  v1,add,help,remove,v0);

     (permuteUnique:rst; null,length==0; sort,list,visited,help,return);

     1 class Solution {
     2     /**
     3      * @param nums: A list of integers.
     4      * @return: A list of unique permutations.
     5      */
     6     public List<List<Integer>> permuteUnique(int[] nums) {
     7     
     8         ArrayList<List<Integer>> results = new ArrayList<List<Integer>>();
     9     
    10         if (nums == null) {
    11             return results;
    12         }
    13     
    14         if(nums.length == 0) {
    15             results.add(new ArrayList<Integer>());
    16             return results;
    17         }
    18 
    19         Arrays.sort(nums);
    20         ArrayList<Integer> list = new ArrayList<Integer>();
    21         int[] visited = new int[nums.length];
    22         for ( int i = 0; i < visited.length; i++){
    23             visited[i] = 0;
    24         }
    25      
    26         helper(results, list, visited, nums);    
    27         return results;
    28     }
    29     
    30     
    31     public void helper(ArrayList<List<Integer>> results, 
    32                    ArrayList<Integer> list, int[] visited, int[] nums) {
    33         
    34         if(list.size() == nums.length) {
    35             results.add(new ArrayList<Integer>(list));
    36             return;
    37         }
    38         
    39         for(int i = 0; i < nums.length; i++) {
    40             if ( visited[i] == 1 || ( i != 0 && nums[i] == nums[i - 1]
    41             && visited[i-1] == 0)){
    42                 continue;
    43             }
    44             /*
    45             上面的判断主要是为了去除重复元素影响。
    46             比如,给出一个排好序的数组,[1,2,2],那么第一个2和第二2如果在结果中互换位置,
    47             我们也认为是同一种方案,所以我们强制要求相同的数字,原来排在前面的,在结果
    48             当中也应该排在前面,这样就保证了唯一性。所以当前面的2还没有使用的时候,就
    49             不应该让后面的2使用。
    50             */
    51             visited[i] = 1;
    52             list.add(nums[i]);
    53             helper(results, list, visited, nums);
    54             list.remove(list.size() - 1);
    55             visited[i] = 0;
    56         }
    57      } 
    58 }
    View Code

    17.Subsets:http://www.lintcode.com/en/problem/subsets/

    子集:(定义pos,作为递归的起点)

    (helper(rst,list,nums,pos); add; for(pos)add,helper(i+1),remove)

    (subSet:异常处理(null/length==0)rst;  sort,list,helper(,,,0),return);

     1 public class Solution {
     2     public ArrayList<ArrayList<Integer>> subsets(int[] num) {
     3         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
     4         if(num == null || num.length == 0) {
     5             return result;
     6         }
     7         ArrayList<Integer> list = new ArrayList<Integer>();
     8         Arrays.sort(num);  
     9         subsetsHelper(result, list, num, 0);
    10 
    11         return result;
    12     }
    13 
    14 
    15     private void subsetsHelper(ArrayList<ArrayList<Integer>> result,
    16         ArrayList<Integer> list, int[] num, int pos) {
    17 
    18         result.add(new ArrayList<Integer>(list));
    19 
    20         for (int i = pos; i < num.length; i++) {
    21 
    22             list.add(num[i]);
    23             subsetsHelper(result, list, num, i + 1);
    24             list.remove(list.size() - 1);
    25         }
    26     }
    27 }
    View Code

    18.Subsets II:http://www.lintcode.com/en/problem/subsets-ii/

    带重复数字的子集:(在循环开始就需要判断它是否为重复数字,如果是,那么只执行first one);(注意判断语句i>pos要在前,不然会出现数组[-1]错误)

    (helper(rst,list,nums,pos); add; for(pos)if(&&) add,helper(i+1),remove)

    (subSet:(null,length); sort,list,helper,return)

     1 class Solution {
     2     /**
     3      * @param nums: A set of numbers.
     4      * @return: A list of lists. All valid subsets.
     5      */
     6     public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] nums) {
     7         // write your code here
     8         ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
     9         if (nums.length == 0 || nums == null){
    10             return rst;
    11         }
    12         Arrays.sort(nums);
    13         ArrayList<Integer> list = new ArrayList<Integer>();
    14         helper(rst, list, nums, 0);
    15         return rst;
    16     }
    17     public void helper(ArrayList<ArrayList<Integer>> rst, ArrayList<Integer> list,
    18     int[] nums, int pos){
    19         rst.add(new ArrayList<Integer>(list));
    20         for (int i = pos; i < nums.length; i++){
    21             if (i > pos && nums[i] == nums[i - 1]){
    22                 continue;
    23             }
    24             list.add(nums[i]);
    25             helper(rst, list, nums, i + 1);
    26             list.remove(list.size() - 1);
    27         }
    28     }
    29 }
    View Code

    22. Flatten List:http://www.lintcode.com/en/problem/flatten-list/

    平面列表:嵌套数组转为纯数字数组;recursion(题目方法的说明没太看懂,但根据方法名大概就可以推出了)(方法总漏掉括号()!!);

     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 public class Solution {
    22 
    23     // @param nestedList a list of NestedInteger
    24     // @return a list of integer
    25     public List<Integer> flatten(List<NestedInteger> nestedList) {
    26         // Write your code here
    27         List<Integer> rst = new ArrayList<Integer>();
    28         for (NestedInteger ele : nestedList){
    29             if (ele.isInteger()){
    30                 rst.add(ele.getInteger());
    31             } else {
    32                 rst.addAll(flatten(ele.getList()));
    33             }
    34         }
    35         return rst;
    36     }
    37 }
    View Code

    28.Search a 2D Matrix:http://www.lintcode.com/en/problem/search-a-2d-matrix/

    搜索二维矩阵:

    for循环(不用考虑异常,因为异常是 for循环条件不满足,不会执行)

     1 public class Solution {
     2     /**
     3      * @param matrix, a list of lists of integers
     4      * @param target, an integer
     5      * @return a boolean, indicate whether matrix contains target
     6      */
     7     public boolean searchMatrix(int[][] matrix, int target) {
     8         // write your code here
     9         for (int i = 0; i < matrix.length; i++){
    10             for(int j = 0; j < matrix[0].length; j++){
    11                 if(matrix[i][j] == target){
    12                     return true;
    13                 }
    14             }
    15         }
    16         return false;
    17     }
    18 }  
    View Code

    两次BinarySearch:(第一次search确定row,第二次确定col;)

    (if if; while(+1<) matrix[mid][0] mid,mid; if(<=)row=end/start false;  while()matrix[row][mid]正常binarySearch )

    (注意:第一次的while必须是(start+1<end),对应的if内=mid,=mid  反例:[1,2][3,4][5,6][7,8][9,10] search 6;如果用mid+1,那么或判断错误--start=4(7),end=5(9))

    (注意:mid的定义必须在while内部,总是写错!  注意: end=length-1!!)

    (判断row的准确位置,if(=end) if(=start) else(false 例如:num < start的情况) )

    我的解法:第二次正常binarySearch 范围用了(<=),判断用的mid-1/mid+1;

     1 public class Solution {
     2     /**
     3      * @param matrix, a list of lists of integers
     4      * @param target, an integer
     5      * @return a boolean, indicate whether matrix contains target
     6      */
     7     public boolean searchMatrix(int[][] matrix, int target) {
     8         // write your code here
     9         if (matrix == null || matrix.length == 0){
    10             return false;
    11         }
    12         if (matrix[0] == null || matrix[0].length == 0){
    13             return false;
    14         }
    15         int start = 0;
    16         int end = matrix.length - 1;
    17         int row ;
    18         while (start + 1 < end) {
    19             int mid = start + (end - start)/2;
    20             if (matrix[mid][0] == target){
    21                 return true;
    22             } else if (matrix[mid][0] < target) {
    23                 start = mid ;
    24             } else {
    25                 end = mid ;
    26             }
    27         }
    28         if (matrix[end][0] <= target){
    29             row = end;
    30         } else if (matrix[start][0] <= target){
    31             row = start;
    32         } else {
    33             return false;
    34         }
    35      
    36         start = 0;
    37         end = matrix[0].length - 1;
    38         while (start <= end) {
    39             int mid = start + (end - start)/2;
    40             if (matrix[row][mid] == target){
    41                 return true;
    42             } else if (matrix[row][mid] < target) {
    43                 start = mid + 1;
    44             } else {
    45                 end = mid - 1;
    46             }
    47         }
    48         return false;
    49     }
    50 }
    View Code

    九章解法:两次都是(+1<),判断为mid,并且需要额外判断start,end;  (虽然有的时候不必要,但好处是模版化!!不用担心异常情况,比如上面的反例;)

     1 public class Solution {
     2     public boolean searchMatrix(int[][] matrix, int target) {
     3         if (matrix == null || matrix.length == 0) {
     4             return false;
     5         }
     6         if (matrix[0] == null || matrix[0].length == 0) {
     7             return false;
     8         }
     9         
    10         int row = matrix.length;
    11         int column = matrix[0].length;
    12         
    13         // find the row index, the last number <= target 
    14         int start = 0, end = row - 1;
    15         while (start + 1 < end) {
    16             int mid = start + (end - start) / 2;
    17             if (matrix[mid][0] == target) {
    18                 return true;
    19             } else if (matrix[mid][0] < target) {
    20                 start = mid;
    21             } else {
    22                 end = mid;
    23             }
    24         }
    25         if (matrix[end][0] <= target) {
    26             row = end;
    27         } else if (matrix[start][0] <= target) {
    28             row = start;
    29         } else {
    30             return false;
    31         }
    32         
    33         // find the column index, the number equal to target
    34         start = 0;
    35         end = column - 1;
    36         while (start + 1 < end) {
    37             int mid = start + (end - start) / 2;
    38             if (matrix[row][mid] == target) {
    39                 return true;
    40             } else if (matrix[row][mid] < target) {
    41                 start = mid;
    42             } else {
    43                 end = mid;
    44             }
    45         }
    46         if (matrix[row][start] == target) {
    47             return true;
    48         } else if (matrix[row][end] == target) {
    49             return true;
    50         }
    51         return false;
    52     }
    53 }
    View Code

    一次BinarySearch:(将Matrix看成m*n长的list,mid对应的number=Matrix[mid/col][mid%col]两个都是col,别写错了);

    (1.两组异常(null,len;null,len);2.start,end,row,col,mid,num;while(<=),if()start=+1;end=-1);

    (注意,while里的条件(<=),对应下面的是mid+1和mid-1)(九章里解法是(+1<),对应=mid,=mid,同时必须要单独列出start和end情况,不明白为什么要这样求解);

    (ps:mid=s+(e-s)/2 而不用 (e+s)/2目的是防止e和s都很大时溢出的情况)

     1 public class Solution {
     2     /**
     3      * @param matrix, a list of lists of integers
     4      * @param target, an integer
     5      * @return a boolean, indicate whether matrix contains target
     6      */
     7     public boolean searchMatrix(int[][] matrix, int target) {
     8         // write your code here
     9         if (matrix == null || matrix.length == 0){
    10             return false;
    11         }
    12         if (matrix[0] == null || matrix[0].length == 0){
    13             return false;
    14         }
    15         int start = 0;
    16         int row = matrix.length;
    17         int col = matrix[0].length;
    18         int end = row * col - 1;
    19         while (start <= end){
    20             int mid = start + (end - start) / 2;
    21             int num = matrix[mid / col][mid % col];
    22             if (num == target){
    23                 return true;
    24             } else if (num < target){
    25                 start = mid + 1;
    26             } else {
    27                 end = mid - 1;
    28             }
    29         }
    30         return false;
    31     }
    32 }
    View Code

    29.Interleaving String:http://www.lintcode.com/en/problem/interleaving-string/

    交叉字符串:(二维动态规划1.异常判断length;  2.一个循环判断s3前几个字符的出处, s3=s1 [i][0]/s3=s2 [0][j];  3.两个for循环判断interleaved[i][j]);

    (1.if; 2.bo [0][0]; 3.for(i)(j) if(i-1)(j-1); 4.for(ij) if(i+j-1 && iter[i-1][j] ||) 5.return[len()][len()])

    (几个错误点:1.首先判断长度;初始化[len+1][len+1],[0][0] 2.for条件[1,len()]; 3.String.length()是方法,要加括号; 4.if 判断为[i-1]; 5.return[len][len])

    (因为二维数字里多了首位[0,0] charAt(j-1)表示第j位,而interleaved[i][j-1]表示第j-1个数)

    s1, s2只有两个字符串,因此可以展平为一个二维地图,判断是否能从左上角走到右下角。

    当s1到达第i个元素,s2到达第j个元素:

    地图上往右一步就是s2[j-1]匹配s3[i+j-1]。

    地图上往下一步就是s1[i-1]匹配s3[i+j-1]。

     1 public class Solution {
     2     public boolean isInterleave(String s1, String s2, String s3) {
     3         if (s1.length() + s2.length() != s3.length()) {
     4             return false;
     5         }
     6         
     7         boolean [][] interleaved = new boolean[s1.length() + 1][s2.length() + 1];
     8         interleaved[0][0] = true;
     9         
    10         for (int i = 1; i <= s1.length(); i++) {
    11             if(s3.charAt(i - 1) == s1.charAt(i - 1) && interleaved[i - 1][0])
    12                 interleaved[i][0] = true;
    13         }
    14         
    15         for (int j = 1; j <= s2.length(); j++) {
    16             if(s3.charAt(j - 1) == s2.charAt(j - 1) && interleaved[0][j - 1])
    17                 interleaved[0][j] = true;
    18         }
    19         
    20         for (int i = 1; i <= s1.length(); i++) {
    21             for (int j = 1; j <= s2.length(); j++) {
    22                 if(((s3.charAt(i + j - 1) == s1.charAt(i - 1) && interleaved[i - 1][j]))
    23                     || ((s3.charAt(i + j - 1)) == s2.charAt(j - 1) && interleaved[i][j - 1]))
    24                 interleaved[i][j] = true;
    25             }
    26         }
    27         
    28         return interleaved[s1.length()][s2.length()];
    29     }
    30 }
    View Code

    30.Insert Interval: http://www.lintcode.com/en/problem/insert-interval/

    插入区间:(定义pos记录位置;newInterval和interval无重叠时,小于new的pos++,并且都可直接add;最后再add(pos,new); 有重叠时,先把无重叠部分add,在把重叠的几个区间合并add)

    (1.if; 2.rst,pos; 3.for()if(<)pos++,add,elseif(>)add else(min,max) 4.add(pos,newInter) 5.return);

     1 public class Solution {
     2     public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
     3         if (newInterval == null || intervals == null) {
     4             return intervals;
     5         }
     6 
     7         ArrayList<Interval> results = new ArrayList<Interval>();
     8         int insertPos = 0;
     9 
    10         for (Interval interval : intervals) {
    11             if (interval.end < newInterval.start) {
    12                 results.add(interval);
    13                 insertPos++;
    14             } else if (interval.start > newInterval.end) {
    15                 results.add(interval);
    16             } else {
    17                 newInterval.start = Math.min(interval.start, newInterval.start);
    18                 newInterval.end = Math.max(interval.end, newInterval.end);
    19             }
    20         }
    21 
    22         results.add(insertPos, newInterval);
    23 
    24         return results;
    25     }
    26 }
    View Code

    31.Partition Array: http://www.lintcode.com/en/problem/partition-array/

    数组划分:(todo)

    32.Minimum Window Substring:http://www.lintcode.com/en/problem/minimum-window-substring/

    最小子串覆盖:

  • 相关阅读:
    TV 丽音(NICAM)功能
    TV TimeShift和PVR的区别
    VGA、DVI、HDMI三种视频信号接口
    单词记忆
    gdb调试的基本使用
    Shell中字符串的切割、拼接、比较、替换
    I2C通信基本原理及其实现
    为什么单片机需要时钟系统,时钟信号在单片机中扮演怎样的角色?
    HDMI热插拔检测原理
    HDMI接口之HPD(热拔插)
  • 原文地址:https://www.cnblogs.com/buwenyuwu/p/6141848.html
Copyright © 2011-2022 走看看