1.连续子数组的最大和
举几个例子:
数组:[1, -2, 3, 5, -3, 2]应返回8.
数组:[-9, -2, -5, -3, -4]应返回-2.
public class FindGreatestSumOfSubArray {
public static void main(String[] args) {
// int[] array = { 6, -3, -2, 7, -15, 1, 2, 2 };
// int[] array = { -9, -2, -3, -5, -3 };
int[] array = {};
System.out.println(findSum(array));
}
public static int findSum(int[] array) {
int max = Integer.MIN_VALUE;
int len = array.length;
int sum;
if (len == 0) {
return 0;
}
for (int i = 0; i < len; i++) {
sum = 0;
for (int j = i; j < len; j++) {
sum += array[j];
if (sum > max) {
max = sum;
}
}
}
return max;
}
}
2.第一个只出现一次的字符的位置
题目描述:
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符的位置。若为空串,返回-1。位置索引从0开始
import java.util.HashMap;
public class Solution {
public static int FirstNotRepeatingChar(String str) {
int index = -1;
if(str == "" || str == null)
return index;
//map键存放的是字符,值存放的是该字符出现的次数
HashMap<Character, Integer>map = new HashMap<>();
for(int i = 0; i < str.length(); i++){
//遍历字符串
Character ch = str.charAt(i);
//判断该字符在map中是否存在,若为空 则是首次出现,值存为1
if(map.get(ch) == null){
map.put(ch, 1);
}else{
//若不为空,则值加1
int count = map.get(ch);
map.put(ch, ++count);
}
}
//再次遍历字符串,map值为1的即为第一个只出现一次的,返回下标
for(int i = 0; i < str.length(); i++){
Character ch = str.charAt(i);
if(map.get(ch) == 1){
index = i;
break;
}
}
return index;
}
}