Skip to content

Commit f40ff8f

Browse files
committed
add leetcode: offer-39-66
1 parent a7a9d7d commit f40ff8f

2 files changed

+75
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package offer;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* @author : CodeWater
8+
* @create :2022-07-15-21:51
9+
* @Function Description :39.数组中出现次数超过一半的数字
10+
*/
11+
public class _39TheNumberOfMoreThanHalfOfTheArrayAppearsMoreThanHalf {
12+
//==========================hashmap============================
13+
class Solution {
14+
public int majorityElement(int[] nums) {
15+
Map<Integer , Integer> hash = new HashMap<>();
16+
for( int num : nums ){
17+
if( hash.containsKey(num) ) hash.put(num , hash.get(num) + 1 );
18+
else hash.put( num , 1 );
19+
}
20+
for( Map.Entry<Integer , Integer> entry : hash.entrySet() ){
21+
if( entry.getValue() > nums.length / 2 ) return entry.getKey();
22+
}
23+
return -1;
24+
}
25+
}
26+
27+
//==========================摩尔投票法============================
28+
class Solution2 {
29+
public int majorityElement(int[] nums) {
30+
// x假定是出现次数最多的众数 votes票数
31+
int x = 0 , votes = 0;
32+
for( int num : nums ){
33+
// 票数为0是 假定当前num是众数
34+
if(votes == 0 ) x = num;
35+
// 判断num是不是上一轮选定的众数x 是的话票数+1 , 不是-1
36+
votes += num == x ? 1 : -1 ;
37+
}
38+
// 最终众数会赋给x , 其余的都会在正负抵消
39+
return x;
40+
}
41+
}
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package offer;
2+
3+
/**
4+
* @author : CodeWater
5+
* @create :2022-07-15-23:13
6+
* @Function Description :66.构建乘积数组
7+
*
8+
*/
9+
public class _66BuildAMultiplicationGroup {
10+
class Solution {
11+
// 题解,看图对比代码比较好理解https://leetcode.cn/problems/gou-jian-cheng-ji-shu-zu-lcof/solution/mian-shi-ti-66-gou-jian-cheng-ji-shu-zu-biao-ge-fe/
12+
public int[] constructArr(int[] a) {
13+
int len = a.length;
14+
if( len == 0 ) return new int[0];
15+
int[] b = new int[len];
16+
b[0] = 1;
17+
18+
// 正向遍历求三角,从1开始,依次递增乘积
19+
for( int i = 1 ; i < len ; i++ ){
20+
b[i] = b[i - 1] * a[i - 1];
21+
}
22+
// 正向遍历上一个下标会储存前面的乘积,倒序遍历只能开一个temp临时存储
23+
int temp = 1;
24+
// 倒序遍历,从倒数第二个开始,依次递增乘积
25+
for( int i = len - 2 ; i >= 0 ; i-- ){
26+
temp *= a[i + 1];
27+
b[i] *= temp;
28+
}
29+
30+
return b;
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)