O(nlogn) Algorithm - Find three evenly spaced ones within binary string

前端 未结 30 2995
刺人心
刺人心 2020-11-28 00:07

I had this question on an Algorithms test yesterday, and I can\'t figure out the answer. It is driving me absolutely crazy, because it was worth about 40 points. I figure

30条回答
  •  半阙折子戏
    2020-11-28 00:56

    I think I have found a way of solving the problem, but I can't construct a formal proof. The solution I made is written in Java, and it uses a counter 'n' to count how many list/array accesses it does. So n should be less than or equal to stringLength*log(stringLength) if it is correct. I tried it for the numbers 0 to 2^22, and it works.

    It starts by iterating over the input string and making a list of all the indexes which hold a one. This is just O(n).

    Then from the list of indexes it picks a firstIndex, and a secondIndex which is greater than the first. These two indexes must hold ones, because they are in the list of indexes. From there the thirdIndex can be calculated. If the inputString[thirdIndex] is a 1 then it halts.

    public static int testString(String input){
    //n is the number of array/list accesses in the algorithm
    int n=0;
    
    //Put the indices of all the ones into a list, O(n)
    ArrayList ones = new ArrayList();
    for(int i=0;i= input.length()){
                break;
            }
    
            n++;
            if(input.charAt(thirdIndex) == '1'){
                //This case is satisfied if it has found three evenly spaced ones
                //System.out.println("This one => " + input);
                return n;
            }
        }
    }
    
    return n;
    

    }

    additional note: the counter n is not incremented when it iterates over the input string to construct the list of indexes. This operation is O(n), so it won't have an effect on the algorithm complexity anyway.

提交回复
热议问题