zoukankan      html  css  js  c++  java
  • Leetcode -- Day13

    Question 1

    Add Binary

    Given two binary strings, return their sum (also a binary string).

    For example,
    a = "11"
    b = "1"
    Return "100".

    Firslty I wirte a very direct and kind of brute forch method. Just consider each case of sum 1, 0, 2, 3 for aNum + bNum + carry by switch case.

     1 public class Solution {
     2     
     3     String result = "";
     4     int carry = 0;
     5     
     6     public String addBinary(String a, String b) {
     7         if (a.length() == 0 )
     8             return b;
     9         else if (b.length() == 0)
    10             return a;
    11         
    12         
    13         int alen = a.length()-1;
    14         int blen = b.length()-1;
    15         
    16         
    17         while (alen >= 0 && blen >=0){
    18             int aNum = a.charAt(alen) - '0';
    19             int bNum = b.charAt(blen) - '0';
    20             calculator(aNum + bNum + carry);
    21             alen --;
    22             blen --;
    23         }
    24         
    25         while (alen >= 0){
    26             int aNum = a.charAt(alen) - '0';
    27             calculator(aNum + carry);
    28             alen --;
    29         }
    30         
    31         while (blen >= 0){
    32             int bNum = b.charAt(blen) - '0';
    33             calculator(bNum + carry);
    34             blen --;
    35         }
    36         
    37         if (carry == 1)
    38             result = "1" + result;
    39         
    40         return result;
    41     }
    42     
    43     public void calculator(int sum){
    44         switch(sum){
    45             case 0:
    46                 result = "0" + result;
    47                 break;
    48             case 1:
    49                 result = "1" + result;
    50                 carry = 0;
    51                 break;
    52             case 2:
    53                 result = "0" + result;
    54                 carry = 1;
    55                 break;
    56             case 3:
    57                 result = "1" + result;
    58                 carry = 1;
    59                 break;
    60         }
    61     }
    62 }

    The other way does not use switch case but use %2 or /2 to defind carry and sum, which is much clear and shorter. 

     1 public String addBinary(String a, String b) {
     2         if (a.length() == 0 )
     3             return b;
     4         else if (b.length() == 0)
     5             return a;
     6             
     7         String result = "";
     8         int carry = 0;
     9         
    10         int len = Math.max(a.length(), b.length());
    11         
    12         for (int i = 0; i < len; i ++){
    13             int aNum = 0;
    14             int bNum = 0;
    15             if (i < a.length())
    16                 aNum = a.charAt(a.length() - 1 - i) - '0';
    17             if (i < b.length())
    18                 bNum = b.charAt(b.length() - 1 - i) - '0';
    19             
    20             int sum = aNum + bNum + carry;
    21             result = sum%2 + result;
    22             carry = sum / 2;
    23         }
    24         
    25         if (carry == 1)
    26             result = "1" + result;
    27         
    28         return result;
    29         
    30     }

    n-sum problem 

    Question 2

    Two Sum

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    solution 1: Brute force. O(n*n)

     1     public int[] twoSum(int[] nums, int target) {
     2         if(nums.length == 0)
     3             return null;
     4        
     5         for (int i = 0; i < nums.length; i ++){
     6             for (int j = i+1; j < nums.length; j ++){
     7                 if (nums[i] + nums[j] == target){
     8                     int[] result = new int[]{i+1, j+1};
     9                     return result;
    10                 }
    11             }
    12         }
    13         return null;
    14     }

    solution 2: sort and binary search. O(n+nlogn+n+n) = O(nlogn)

     1 public int[] twoSum(int[] nums, int target) {
     2         if(nums.length == 0)
     3             return null;
     4             
     5         int[] result = new int[2];
     6        
     7         int[] copyNums = new int[nums.length];
     8         System.arraycopy(nums, 0, copyNums, 0, nums.length);  
     9         Arrays.sort(copyNums);
    10         
    11         int low = 0; 
    12         int high = copyNums.length-1;
    13         
    14         while (low < high){
    15             int sum = copyNums[low] + copyNums[high];
    16             if (sum == target){
    17                 result[0] = copyNums[low];
    18                 result[1] = copyNums[high];
    19                 break;
    20             }
    21             else if (sum < target)
    22                 low ++;
    23             else
    24                 high --;
    25         }
    26         
    27         if (result.length == 0)
    28             return null;
    29             
    30         else{
    31             int index1 = -1, index2 = -1;
    32             for (int i = 0; i < nums.length; i ++){
    33                 if (result[0] == nums[i] && index1 == -1)
    34                     index1 = i + 1;
    35                 else if (result[1] == nums[i] && index2 == -1)
    36                     index2 = i + 1;
    37             }
    38             
    39             result[0] = index1;
    40             result[1] = index2;
    41             Arrays.sort(result);
    42             return result;
    43         }
    44     }

    solution 2: hashmap. O(n)

     1     public int[] twoSum(int[] nums, int target) {
     2         if(nums.length < 2 || nums == null)
     3             return null;
     4             
     5         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
     6         int[] res = new int[2];
     7         
     8         for (int i = 0; i < nums.length; i ++){
     9             if (!map.containsKey(target-nums[i]))
    10                 map.put(nums[i], i + 1);
    11             else{
    12                 res[0] = map.get(target-nums[i]);
    13                 res[1] = i + 1;
    14                 break;
    15             }
    16         }
    17         return res;
    18     }

     Question 3

    3Sum

    Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

    Note:

    • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
    • The solution set must not contain duplicate triplets.
        For example, given array S = {-1 0 1 2 -1 -4},
        A solution set is:
        (-1, 0, 1)
        (-1, -1, 2)

     I feel this is much more difficult than the before 2 sum one. We need three pointers here. And I found a trick, with which you did not write tree times list.add(element).

    Arrays.asList(a, b, c) 
     1     public List<List<Integer>> threeSum(int[] nums) {
     2         List<List<Integer>> triples = new ArrayList();
     3         if (nums.length < 3)
     4             return triples;
     5         
     6         Arrays.sort(nums);
     7         int i = 0, last = nums.length - 1;
     8         while (i < last) {
     9             int a = nums[i], j = i+1, k = last;
    10             while (j < k) {
    11                 int b = nums[j], c = nums[k], sum = a+b+c;
    12                 if (sum == 0) triples.add(Arrays.asList(a, b, c));
    13                 if (sum <= 0) while (nums[j] == b && j < k) j++;
    14                 if (sum >= 0) while (nums[k] == c && j < k) k--;
    15             }
    16             while (nums[i] == a && i < last) i++;
    17         }
    18         return triples;
    19     }

    Question 4

    3Sum Closest

    Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

        For example, given array S = {-1 2 1 -4}, and target = 1.
    
        The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
     1 public int threeSumClosest(int[] nums, int target) {
     2         if (nums.length < 3)
     3             return Integer.MAX_VALUE;
     4         
     5         Arrays.sort(nums);
     6         int result = nums[0] + nums[1] + nums[2];
     7             
     8         int i = 0;
     9         int last = nums.length - 1;
    10         while (i < last){
    11             int a = nums[i];
    12             int j = i + 1;
    13             int k = last;
    14             while (j < k){
    15                 int b = nums[j];
    16                 int c = nums[k];
    17                 int sum = a + b + c;
    18                 int diff = Math.abs(target - sum);
    19                 
    20                 if (diff < Math.abs(target - result)){
    21                     result = sum;
    22                 }
    23                 
    24                 if (diff == 0)
    25                     return sum;
    26                 else if (sum > target){
    27                     while (nums[k] == c && j < k)
    28                         k --;
    29                 }
    30                 else if (sum < target){
    31                     while (nums[j] == b && j < k)
    32                         j ++;
    33                 }
    34             }
    35             while (nums[i] == a && i < k)
    36                 i ++;
    37         }
    38         return result;
    39         
    40     }
    
    
    
     
  • 相关阅读:
    perl 安装Rex
    salt-stack 客户端运行需要安装python
    Lock wait timeout exceeded
    敏捷BI与数据驱动机制
    MyBatis传入参数为list、数组、map写法
    angular2.js:2 Uncaught ReferenceError: System is not defined
    谈谈企业的数据工作!——企业的数据分析能力金字塔
    SyntaxError: inconsistent use of tabs and spaces in indentation
    Eclipse Save Action功能
    TypeError: unicode strings are not supported, please encode to bytes: 'hu'
  • 原文地址:https://www.cnblogs.com/timoBlog/p/4662843.html
Copyright © 2011-2022 走看看