剑指offer---连续子数组的最大和、第一个只出现一次的字符的位置

该博客探讨了两个编程问题:如何找到数组中连续子数组的最大和,例如在[1, -2, 3, 5, -3, 2]中最大和为8;以及在字符串中找到第一个只出现一次的字符的位置,如在空串中返回-1。" 53282262,5513243,Java分隔符匹配算法解析,"['编程', 'Java', '算法', '数据结构', '语法解析']
摘要由CSDN通过智能技术生成

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值