Day6 LeetCode 43 46 53
1. 字符串相乘(LeetCode 43 题)
1.1题目
1.2思路
如果直接暴力解会出现数字越界问题,同时也不允许直接转为整数来处理。
介绍一下比较巧妙的方法,就是把两个数乘法转化为多个数的乘法,比如123*456 = 123*6+123*50+123*400 这样可以把乘法进行单个数乘法以及求和。同时每次只计算我们的最后一个数字,以及进位值。不过如果对数据进行字符串拼接的方法进行计算,会导致计算量过大,这里采用一个巧妙的容器,int列表来暂存我们的结果。如果两个数进行相乘(长度分别为n,m),取值范围为m+n-1:n+m。因此我们可以构建m+n长度的数组进行存储。如果取值为m+n-1,首位空为0即可。
1.3代码
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0")||num2.equals("0")) return "0";
int [] res = new int[num1.length()+num2.length()];
for (int i = num1.length()-1; i >=0 ; i--) {
int n1 = num1.charAt(i)-'0';
for (int j = num2.length()-1; j >=0 ; j--) {
int n2 = num2.charAt(j)-'0';
int sum = (res[i+j+1]+n1*n2);
res[i+j+1] = sum %10;
res[i+j] += sum/10;
}
}
StringBuilder reslist = new StringBuilder();
for (int i = 0; i < res.length; i++) {
if (i==0&&res[i]==0) continue;
reslist.append(res[i]);
}
return reslist.toString();
}
}
2. 全排列(LeetCode 46 题)
2.1题目
2.2思路
这道题就是一个排列组合问题,遇到这种问题我们可把复杂的问题逐渐化简到最小,通过回溯的方法化简复杂问题。
也就是首先以每个数字作为头,有n种排列,其次把下一次余下的数据看成新的一部分。(也就是对n-1的数据量求得排列)逐渐化简问题至1。
2.3代码
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> output = new ArrayList<Integer>();
for (int num : nums) {
output.add(num);
}
int n = nums.length;
backtrack(n, output, res, 0);
return res;
}
public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
// 所有数都填完了
if (first == n) {
res.add(new ArrayList<Integer>(output));
}
for (int i = first; i < n; i++) {
// 动态维护数组
Collections.swap(output, first, i);
// 继续递归填下一个数
backtrack(n, output, res, first + 1);
// 撤销操作
Collections.swap(output, first, i);
}
}
}
3. 最大子序和(LeetCode 53 题)
3.1题目
3.2思路
在[-2,1,-3,4,-1,2,1,-5,4]序列中,从头开始遍历,指针指向第一个元素-2.当后面有元素为正时舍弃-2,直接把最大前缀改为后面出现的正数1.或者最大的一个复数。
也就是说我们求前面元素最大和是找到非负中最大的集合或者最大的复数。然后不断记录集合,遍历结束记得到结果。
3.3代码
class Solution {
public int maxSubArray(int[] nums) {
int pre = 0, maxAns = nums[0];
for (int x : nums) {
pre = Math.max(pre + x, x);
maxAns = Math.max(maxAns, pre);
}
return maxAns;
}
}