当前位置:网站首页>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;
}
}边栏推荐
- Dip1000 implicitly tagged with fields
- Sqli labs Level 2
- Solution and analysis of Hanoi Tower problem
- Pointer initialization
- Mysql安装时mysqld.exe报`应用程序无法正常启动(0xc000007b)`
- Kubedm deploys kubernetes v1.23.5 cluster
- HCIA—应用层
- [blackmail virus data recovery] suffix Rook3 blackmail virus
- PCL calculates the intersection of three mutually nonparallel planes
- [blackmail virus data recovery] suffix Crylock blackmail virus
猜你喜欢

Minecraft空岛服开服

HCIA - data link layer

Googlenet network explanation and model building

C language custom type enumeration, Union (clever use of enumeration, calculation of union size)

将一串数字顺序后移

MYSQL安装出现问题(The service already exists)

sqli-labs第1关

Openfeign is easy to use

Openfeign facile à utiliser

STM32 new project (refer to punctual atom)
随机推荐
gocv边界填充
[blackmail virus data recovery] suffix Crylock blackmail virus
QT drag event
汉诺塔问题的求解与分析
整理秒杀系统的面试必备!!!
Routing foundation - dynamic routing
C language custom types - structure, bit segment (anonymous structure, self reference of structure, memory alignment of structure)
C Gaode map obtains the address according to longitude and latitude
Sqli labs level 8 (Boolean blind note)
Mutex
1、 QT's core class QObject
MYSQL安装出现问题(The service already exists)
随笔:RGB图像颜色分离(附代码)
OpenFeign 簡單使用
Solid principle: explanation and examples
Googlenet network explanation and model building
Hcia - Application Layer
gocv opencv exit status 3221225785
Installing Oracle database 19C for Linux
OpenShift 部署应用