算法面试题(1)
1、最长不重复字符串
(如:abcabcd,第一步会先遇到重复字符a,则把起始的a删除,再重b开始查不重复的字符串,则为遇到重复,就去除最左端的字符)
public static void main(String[] args) {
String str = "ababcabcd";
//i记录起始字符, j记录当前循环的字符, max最大不重复字符串长度
int i = 0, j = 0, max = 0;
Set<Character> set = new HashSet<>();
while (j < str.length()) {
if (!set.contains(str.charAt(j))){
set.add(str.charAt(j));
j++;
}else {
//把起始值删除
set.remove(str.charAt(i));
i++;
}
max = Math.max(max,set.size());
}
System.out.println(max);
System.out.println(set.toString());
}
2、查找旋转数组的最小值
(把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1)
这个问题的中心思想其实就是使用二分查找的方法,逐步的逼近这个最小值
public static int findMin(int a[]) {
int low = 0;
int high = a.length-1;
int mid;
while (low<high) {
mid = (low + high) / 2;
if (a[mid] < a[high]) {
high = mid;//最小值在左半部分
}else {
low = mid + 1;//最小值在右半部分
}
}
return a[low];
}

浙公网安备 33010602011771号