Is "!=" a not valid condition in for loop?


  • 0
    R

    I have done this correctly using the same algorithm with while loop, yet when I tried to use for loop, the code below seems to run into some problems. (the code below is to find out whether the care can start from a given index(startIndex) and finish the circuit)

    if(startIndex<len){
                int total = leftover[startIndex];
                for(int i = startIndex+1;i!=startIndex;i++){
                    total = total + leftover[i];
                    if(total<0)
                    break;
                    if(i==(len))
                    i=0;
                }
                result = total;
            }
    

    After some checking, I found that it should be the problem with the condition "i!=startIndex", is it not allowed in java for such a condition to appear in the for loop?


  • 0
    S

    Seems it is not full code, just a guess. What if len = 1?

    The i in for loop is start from startIndex + 1 which means 1, then leftover[1] is out of range, since there is only 1 element.


  • 0
    R

    Thank you, but I have used other codes to avoid this scenario. And since it output TLE but not indexOutOfRange, the mitigation works, just the condition is somehow incorrect.


  • 0
    L

    you need to use mod to form a loop: when you reach the end of the array, you need to reset it to 0:
    Change the

     for(int i = startIndex+1;i!=startIndex;i++)
    

    to

     for(int i = startIndex+1;i!=startIndex;i = (i + 1) % leftover.length)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.