Compare commits
3 Commits
31b00f672f
...
2e608b6f23
| Author | SHA1 | Date |
|---|---|---|
|
|
2e608b6f23 | |
|
|
86ebccaff6 | |
|
|
f6c17b67da |
|
|
@ -78,7 +78,7 @@
|
|||
<option name="presentableId" value="Default" />
|
||||
<updated>1693822719192</updated>
|
||||
<workItem from="1693822720224" duration="5742000" />
|
||||
<workItem from="1693895305007" duration="4114000" />
|
||||
<workItem from="1693895305007" duration="5015000" />
|
||||
</task>
|
||||
<servers />
|
||||
</component>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
package solution;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class Solution {
|
||||
|
|
@ -25,4 +27,56 @@ public class Solution {
|
|||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ public class test {
|
|||
String s2 = "pwwkew";
|
||||
String s3 = "ckilbkd";
|
||||
String s4 = "dvdf";
|
||||
System.out.println(lengthOfLongestSubstring(s));
|
||||
System.out.println(lengthOfLongestSubstring(s3));
|
||||
|
||||
}
|
||||
public static int lengthOfLongestSubstring(String s) {
|
||||
|
|
|
|||
Loading…
Reference in New Issue