双指针问题(常考)

/**
 * 请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
 * 输入:"abcabcbb"
 * 返回值:3
 * 说明:因为无重复字符的最长子串是"abc",所以其长度为 3。
 */
public class 最长不含重复字符的子字符串 {

    public static int lengthOfLongestSubstring (String s) {
        // 这里必须要用set,使用List会报错
        Set<Character> characters = new LinkedHashSet<>();
        int high = 0;
        int low = 0;
        int count = 0;
        while (high < s.length()){
            while (characters.contains(s.charAt(high))) {
                System.out.println(characters.toString());
                characters.remove(s.charAt(low++));
            }
            characters.add(s.charAt(high++));
            count = Math.max(count,high - low);
        }
        return count;
    }

    public static void main(String[] args) {
        int count = lengthOfLongestSubstring("abcabcbb");
        System.out.println(count);
    }
}
 小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。
但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。
        现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列?
 
public class 双指针算法解决一个数组中的和区间 {

    /**
     * 双指针算法
     * 适合有序数组,找和sum的区间
     */
    public static ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if(sum <= 2) {
            return result;
        }
        int low = 1;
        int high = 2;
        while (high > low) {
            // 等差数列,两数之和公式
            int cur = ((high + low) * (high - low + 1))/2;
            if(cur == sum) {
                ArrayList<Integer> list = new ArrayList<>();
                for (int i = low; i <= high; i++) {
                    list.add(i);
                }
                low++;
                result.add(list);
            }
            if(cur < sum) {
                high++;
            }
            if(cur > sum) {
                low++;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        ArrayList<ArrayList<Integer>> arrayLists = FindContinuousSequence(9);
        System.out.println(arrayLists.toString());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值