Compare commits

..

3 Commits

Author SHA1 Message Date
wangsiyuan 2e608b6f23 更新 test.java 2023-09-05 15:52:25 +08:00
wangsiyuan 86ebccaff6 更新 Solution.java 2023-09-05 15:52:23 +08:00
wangsiyuan f6c17b67da 更新 workspace.xml 2023-09-05 15:52:20 +08:00
3 changed files with 56 additions and 2 deletions

View File

@ -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>

View File

@ -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;
}
}

View File

@ -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) {