diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 3193ccd..207e055 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,10 +2,8 @@ - - - - + + - + - - @@ -212,7 +210,7 @@ - + 1580045439607 @@ -249,7 +247,14 @@ - @@ -261,40 +266,41 @@ - - + - + - + - + - + - + - + - + - + - + @@ -320,10 +326,10 @@ - + - + diff --git a/src/q26/Solution.java b/src/q26/Solution.java new file mode 100644 index 0000000..2d92616 --- /dev/null +++ b/src/q26/Solution.java @@ -0,0 +1,24 @@ +package q26; + +/** + * o(n) + */ +public class Solution { + public int removeDuplicates(int[] nums) { + if (nums.length < 2) { + return nums.length; + } + int c = 0; + for (int i = 1; i < nums.length; i++) { + if (nums[i] != nums[c]) { + c++; + nums[c] = nums[i]; + } + } + return c + 1; + } + + public static void main(String[] args) { + new Solution().removeDuplicates(new int[]{1, 1, 2}); + } +} diff --git a/src/q43/Solution.java b/src/q43/Solution.java new file mode 100644 index 0000000..1871698 --- /dev/null +++ b/src/q43/Solution.java @@ -0,0 +1,47 @@ +package q43; + +/** + * o(n) 可基于乘数某位与被乘数某位相乘产生结果的位置的规律优化 + */ +class Solution { + + public String multiply(String num1, String num2) { + if (num1.equals("0") || num2.equals("0")) { + return "0"; + } + String res = "0"; + + for (int i = num2.length() - 1; i >= 0; i--) { + int carry = 0; + StringBuilder temp = new StringBuilder(); + for (int j = 0; j < num2.length() - 1 - i; j++) { + temp.append(0); + } + int n2 = num2.charAt(i) - '0'; + + for (int j = num1.length() - 1; j >= 0 || carry != 0; j--) { + int n1 = j < 0 ? 0 : num1.charAt(j) - '0'; + int product = (n1 * n2 + carry) % 10; + temp.append(product); + carry = (n1 * n2 + carry) / 10; + } + res = addStrings(res, temp.reverse().toString()); + } + return res; + } + + public String addStrings(String num1, String num2) { + StringBuilder builder = new StringBuilder(); + int carry = 0; + for (int i = num1.length() - 1, j = num2.length() - 1; + i >= 0 || j >= 0 || carry != 0; + i--, j--) { + int x = i < 0 ? 0 : num1.charAt(i) - '0'; + int y = j < 0 ? 0 : num2.charAt(j) - '0'; + int sum = (x + y + carry) % 10; + builder.append(sum); + carry = (x + y + carry) / 10; + } + return builder.reverse().toString(); + } +}