当前位置:网站首页>Leetcode sword finger offer brush questions - day 23
Leetcode sword finger offer brush questions - day 23
2022-07-02 08:53:00 【DEGv587】
Leetcode The finger of the sword Offer How to brush questions :
The finger of the sword Offer 39. A number that appears more than half the times in an array
Solution 1 : Sort library function + Median
class Solution {
public int majorityElement(int[] nums) {
if (nums.length == 0) return -1;
Arrays.sort(nums);
return nums[nums.length / 2];
}
}Solution 2 :hashmap
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums) {
map.put(n, map.getOrDefault(n, 0) + 1);
if (map.get(n) > (nums.length / 2)) {
return n;
}
}
return -1;
}
}Solution 3 : Moore voting , Limit for limit , Left to the end is more than half
class Solution {
public int majorityElement(int[] nums) {
int count = 0, ret = 0;
for (int n : nums) {
if (count == 0) {
ret = n;
++count;
} else {
count = ret == n ? ++count : --count;
}
}
return ret;
}
}The finger of the sword Offer 66. Building a product array
solution : From left to right , Then multiply from right to left
class Solution {
public int[] constructArr(int[] a) {
int len = a.length;
int[] ret = new int[len];
// From left to right
int cur = 1;
for (int i = 0; i < len; ++i) {
ret[i] = cur;
cur *= a[i];
}
// From right to left
cur = 1;
for (int i = len - 1; i >= 0; --i) {
ret[i] *= cur;
cur *= a[i];
}
return ret;
}
}边栏推荐
猜你喜欢
随机推荐
QT -- how to set shadow effect in QWidget
Solid principle: explanation and examples
KubeSphere 虚拟化 KSV 安装体验
gocv图片读取并展示
Dip1000 implicitly tagged with fields
Use Wireshark to grab TCP three handshakes
Mysql安装时mysqld.exe报`应用程序无法正常启动(0xc000007b)`
Driving test Baodian and its spokesperson Huang Bo appeared together to call for safe and civilized travel
sqli-labs第8关(布尔盲注)
整理秒杀系统的面试必备!!!
Qt的右键菜单
图像变换,转置
Minecraft模组服开服
commands out of sync. did you run multiple statements at once
C# 高德地图 根据经纬度获取地址
C # save web pages as pictures (using WebBrowser)
File upload Labs
commands out of sync. did you run multiple statements at once
[flask] ORM one-to-one relationship
Sqli labs level 1









