更新 Solution.java
parent
f6c17b67da
commit
86ebccaff6
|
|
@ -1,6 +1,8 @@
|
||||||
package solution;
|
package solution;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
public class Solution {
|
public class Solution {
|
||||||
|
|
@ -25,4 +27,56 @@ public class Solution {
|
||||||
}
|
}
|
||||||
return ans;
|
return ans;
|
||||||
}
|
}
|
||||||
|
//计算最大价格
|
||||||
|
public static int maxProfit(int[] prices) {
|
||||||
|
if (prices == null || prices.length == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int minPrice = prices[0];
|
||||||
|
int maxProfit = 0;
|
||||||
|
|
||||||
|
for (int price : prices) {
|
||||||
|
// 更新最小价格
|
||||||
|
minPrice = Math.min(minPrice, price);
|
||||||
|
|
||||||
|
// 计算当前价格的潜在利润并更新最大利润
|
||||||
|
int potentialProfit = price - minPrice;
|
||||||
|
maxProfit = Math.max(maxProfit, potentialProfit);
|
||||||
|
}
|
||||||
|
|
||||||
|
return maxProfit;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//哈希映射算法(Hash Mapping Algorithm)用于找出一个数组中的众数(majority element)
|
||||||
|
public int majorityElement(int[] nums) {
|
||||||
|
Map<Integer, Integer> map = new HashMap<>();
|
||||||
|
// maxNum 表示元素,maxCount 表示元素出现的次数
|
||||||
|
int maxNum = 0, maxCount = 0;
|
||||||
|
for (int num: nums) {
|
||||||
|
int count = map.getOrDefault(num, 0) + 1;
|
||||||
|
map.put(num, count);
|
||||||
|
if (count > maxCount) {
|
||||||
|
maxCount = count;
|
||||||
|
maxNum = num;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return maxNum;
|
||||||
|
}
|
||||||
|
//摩尔投票算法(Boyer-Moore Voting Algorithm)来找出数组中的众数
|
||||||
|
public static int majorityElement1(int[] nums) {
|
||||||
|
int candidate = nums[0], count = 1;
|
||||||
|
for (int i = 1; i < nums.length; ++i) {
|
||||||
|
if (count == 0) {
|
||||||
|
candidate = nums[i];
|
||||||
|
count = 1;
|
||||||
|
} else if (nums[i] == candidate) {
|
||||||
|
count++;
|
||||||
|
} else{
|
||||||
|
count--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue