LeetCode | robot can return home

      Holiday time is over half, and adhere to more than an hour to see the book every day, though not much time, but can concentrate on the book look into it. Today, sharing is LeetCode above 657 questions, entitled "Robots can return to origin", which is a simple question.

 

LeetCode exam of 657 questions - whether the robot returns home

      Solution question is also very simple, define the coordinates, and set coordinates (0, 0), and in a given direction to move, in the process of moving to modify the direction of future movement completion judging again whether the coordinates (0, 0 ) can be. code show as below:

 1 bool judgeCircle(char* moves) {
 2     int x = 0;
 3     int y = 0;
 4     
 5     int len = strlen(moves);
 6     
 7     int i;
 8     
 9     for ( i = 0; i < len; i ++ ) {
10         switch ( moves[i] ) {
11             case 'U': {
12                 y ++;
13                 break;
14             }
15             case 'D': {
16                 y --;
17                 break;
18             }
19             case 'L': {
20                 x --;
21                 break;
22             }
23             case 'R': {
24                 x ++;
25                 break;
26             }
27         }
28     }
29     
30     if ( x == 0 && y == 0 ) {
31         return 1;
32     }
33     
34     return 0;
35 }

      LeetCode tips about execution time and memory consumption of code above the code execution time is 8 ms, you can try to be optimized. Imagine if the number of steps is a single-step, certainly not back to square one, while the number of steps is even further back to square one might, it is possible to increase a judge, an increase in code as follows:

. 1  BOOL judgeCircle ( char * Moves) {
 2      int X = 0 ;
 . 3      int Y = 0 ;
 . 4      
. 5      int len = strlen (Moves);
 . 6      
. 7      IF (len% 2 =! 0 ) {
 . 8          return  0 ;
 . 9      }
 10      
. 11      int I;
 12 is      
13 is      // this code is the same as above and 
14      
15      IF (X == 0 && Y == 0 ) {
16         return 1;
17     }
18     
19     return 0;
20 }

      With the addition of the above judgment, the code from the original 8 ms into a 4 ms, it would be greatly improved. I tried to remove the variable y, using only one x variable to solve the problem, but the code will be bug, although LeetCode test case did not test it, but the time has returned 8 ms. As for other solutions, we no longer think of.


Welcome to the concern micro-channel public number: "Code farming UP2U"

Guess you like

Origin www.cnblogs.com/tosser/p/11619800.html