1ms Simple Iterative Java Solution, beat 60%


  • 0
    D
    public class Solution {
        public List<Integer> grayCode(int n) {
            
            List<Integer> rt = new ArrayList<Integer>();
            rt.add(0);
            if ( n == 0 )
                return rt;
            rt.add(1);
            if ( n == 1 )
                return rt;
                
            int old_c = 2, new_c = 4, counter = 1;
            
            while ( old_c != Math.pow(2,n) ) {
                
                for ( int i = 1; i <= new_c - old_c; i++ ) {
                    rt.add( rt.get( old_c - i ) | ( 1 << counter ) );
                }
                
                old_c = new_c;
                new_c *= 2;
                counter++;
            }
            
            return rt;
        }
    }

Log in to reply
 

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