109 lines
3.6 KiB
Java
109 lines
3.6 KiB
Java
package solution;
|
||
|
||
import java.util.*;
|
||
import java.util.stream.Collectors;
|
||
|
||
public class Solution {
|
||
|
||
//给定一个字符串 s ,找出其中不含有重复字符的 最长子串 的长度。
|
||
public static int lengthOfLongestSubstring(String s) {
|
||
// 哈希集合,记录每个字符是否出现过
|
||
Set<Character> occ = new HashSet<Character>();
|
||
int n = s.length();
|
||
// 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动
|
||
int rk = -1, ans = 0;
|
||
for (int i = 0; i < n; ++i) {
|
||
if (i != 0) {
|
||
// 左指针向右移动一格,移除一个字符
|
||
occ.remove(s.charAt(i - 1));
|
||
}
|
||
while (rk + 1 < n && !occ.contains(s.charAt(rk + 1))) {
|
||
// 不断地移动右指针
|
||
occ.add(s.charAt(rk + 1));
|
||
++rk;
|
||
}
|
||
// 第 i 到 rk 个字符是一个极长的无重复字符子串
|
||
ans = Math.max(ans, rk - i + 1);
|
||
}
|
||
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 static 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;
|
||
}
|
||
//合并数组冒泡排序实现
|
||
public static void merge(int[] nums1, int m, int[] nums2, int n) {
|
||
int[] nums= new int[m + n];
|
||
for (int i = 0; i < m + n; i++) {
|
||
if (i < m){
|
||
nums[i] = nums1[i];
|
||
} else {
|
||
nums[i] = nums2[i - m];
|
||
}
|
||
}
|
||
// 冒泡排序
|
||
for (int i = 0; i < nums.length; i++) {
|
||
for (int j = 0; j < nums.length; j++) {
|
||
if (i != j) {
|
||
if (nums[i] < nums[j]){
|
||
int temp = nums[i];
|
||
nums[i] = nums[j];
|
||
nums[j] = temp;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
nums1 = nums;
|
||
String result = Arrays.stream(nums1).mapToObj(String::valueOf).collect(Collectors.joining(",", "[", "]"));
|
||
System.out.println(result);
|
||
}
|
||
}
|