zoukankan      html  css  js  c++  java
  • 算法面试题(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];
        }
    

      

  • 相关阅读:
    基础编程练习题第一波
    TYVJ 1541 八数码
    NOIP 2014 寻找道路
    NOIP2014 解方程
    POJ 3213 矩阵乘法(优化)
    POJ 1523 Tarjan求割点
    POJ 3237 树链剖分+线段树
    SPOJ 375 树链剖分
    NOIP 2012 T2 国王游戏 (贪心+高精)
    POJ 1364 差分约束
  • 原文地址:https://www.cnblogs.com/HHR-SUN/p/12015690.html
Copyright © 2011-2022 走看看