第二十三天——数学
第一题:剑指 Offer 39. 数组中出现次数超过一半的数字
问题描述
思路一:投票法(借鉴大佬思路)
作者:jyd
链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/solution/mian-shi-ti-39-shu-zu-zhong-chu-xian-ci-shu-chao-3/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
代码
class Solution {
public int majorityElement(int[] nums) {
int x = 0, votes = 0;
for(int num : nums){
if(votes == 0) x = num;
if(num == x) votes++;
else votes--;
}
return x;
}
}
空间复杂度和时间复杂度
思路二(排序)
直接排序,然后输出num最中间的值
代码
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
空间复杂度和时间复杂度
思路三(比较)
用for循环比较,相同count加一,然后输出count大于等于数组长度一半
代码
class Solution {
public int majorityElement(int[] nums) {
int num = 0;
for(int i=0;i<nums.length;i++){
int count=0;
for(int j=i+1;j<nums.length;j++){
if(nums[i] == nums[j])
count++;
}
if(count >= nums.length / 2)
num = nums[i];
}
return num;
}
}
空间复杂度和时间复杂度
第二题:剑指 Offer 66. 构建乘积数组
问题描述
思路
借鉴大佬思路
作者:jyd
链接:https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof/solution/mian-shi-ti-66-gou-jian-cheng-ji-shu-zu-biao-ge-fe/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
代码
class Solution {
public int[] constructArr(int[] a) {
int len = a.length;
if(len == 0) return new int[0];
int[] b = new int[len];
b[0] = 1;
int tmp = 1;
for(int i = 1; i < len; i++) {
b[i] = b[i - 1] * a[i - 1];
}
for(int i = len - 2; i >= 0; i--) {
tmp *= a[i + 1];
b[i] *= tmp;
}
return b;
}
}