当前位置:网站首页>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;
}
}边栏推荐
- k8s入门:Helm 构建 MySQL
- STM32 new project (refer to punctual atom)
- Call Stack
- Introduction to the basic concept of queue and typical application examples
- Synchronize files using unison
- Tensorflow2 keras 分类模型
- IP protocol and IP address
- gocv边界填充
- Openshift container platform community okd 4.10.0 deployment
- Detailed explanation of NIN network
猜你喜欢
随机推荐
Network security - summary and thinking of easy-to-use fuzzy tester
Mysql安装时mysqld.exe报`应用程序无法正常启动(0xc000007b)`
C language custom types - structure, bit segment (anonymous structure, self reference of structure, memory alignment of structure)
kubernetes部署loki日志系统
Getting started with k8s: building MySQL with Helm
一、Qt的核心类QObject
将一串数字顺序后移
k8s入门:Helm 构建 MySQL
sqli-labs第8关(布尔盲注)
Synchronize files using unison
HCIA—应用层
Minecraft安装资源包
Minecraft群組服開服
Honeypot attack and defense drill landing application scheme
gocv边界填充
Qt的connect函数和disconnect函数
Essay: RGB image color separation (with code)
Data asset management function
Installing Oracle database 19C RAC on Linux
Connect function and disconnect function of QT
![[untitled]](/img/6c/df2ebb3e39d1e47b8dd74cfdddbb06.gif)








