思路:先将数组排序,遍历前半段数组。当nums[i]==nums[i+length/2]时,该元素即为所求
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int index = 0;
for (int i=0;i<=nums.length/2;i++){
if (nums[i] == nums[i+nums.length/2]){
index = i;
break;
}
}
return nums[index];
}
思路:刚开始用双重循环,超时了。
评论区思路,记录a[i]左侧元素乘积,记录a[i]右侧元素乘积。最终结果为b[i] = left[i] * right[i]
public int[] constructArr(int[] a) {
int[] B = new int[a.length];
// 记录a[i]左侧元素乘积
for (int i=0,sum=1;i<a.length;sum*=a[i],i++){
B[i] = sum;
}
// 记录a[i]右侧元素和并记录 左侧乘积*右侧乘积 为结果
for (int i=a.length-1,sum=1;i>=0;sum*=a[i],i--){
B[i] *= sum;
}
return B;
}