数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
class Solution {
public int majorityElement(int[] nums) {
int res =0;
int count =0;
for(int i=0; i< nums.length; i++){
if(count == 0){
res = nums[i];
count ++;
continue;
}
if(res == nums[i]) {
count++;
} else{
count--;
}
}
return res;
}
}
构建乘积数组
给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B[i] 的值是数组 A 中除了下标 i 以外的元素的积, 即 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法。
输入: [1,2,3,4,5]
输出: [120,60,40,30,24]
提示:
- 所有元素乘积之和不会溢出 32 位整数
a.length <= 100000
class Solution {
public int[] constructArr(int[] a) {
if(a.length == 0){
return new int[0];
}
int[] b = new int[a.length];
b[0] = 1;
for(int i=1; i<a.length; i++){
b[i] = b[i-1] * a[i-1];
}
int temp =1;
for(int i=a.length-2; i>=0; i--){
temp *= a[i+1];
b[i] *= temp;
}
return b;
}
}