Advertisement
Guest User

Jump Game

a guest
Oct 23rd, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. /*  
  2. *   This problem has a nice BFS structure.
  3. *
  4. *   Let's illustrate it using the example nums = [2, 3, 1, 1, 4] in the problem statement.
  5. *   We are initially at position 0. Then we can move at most nums[0] steps from it. So, after one move,
  6. *   we may reach nums[1] = 3 or nums[2] = 1. So these nodes are reachable in 1 move. From these nodes,
  7. *   we can further move to nums[3] = 1 and nums[4] = 4
  8. *   Now you can see that the target nums[4] = 4 is reachable in 2 moves.
  9. *
  10. *   Putting these into codes, we keep two pointers start and end that record the current range of the starting nodes.
  11. *   Each time after we make a move, update start to be end + 1 and end to be the farthest index that can be reached in 1 move
  12. *   from the current [start, end].
  13. *
  14. *   To get an accepted solution, it is important to handle all the edge cases. And the following codes handle all of them in a
  15. *   unified way without using the unclean if statements :-)
  16. */
  17.  
  18. class Solution {
  19. public:
  20.     int jump(vector<int>& nums) {
  21.         int start = 0; int end = 0; int maxEnd = 0; int distance = 0;
  22.         int n = nums.size();
  23.         while (end < n -1)
  24.         {
  25.             distance++;    
  26.             for (int i = start; i <= end; i++)
  27.             {
  28.                 if (i+ nums[i] >= n-1) {
  29.                     return distance;
  30.                 }
  31.                 maxEnd = max(maxEnd, i + nums[i]);
  32.             }
  33.             start = end + 1;
  34.             end = maxEnd;
  35.         }
  36.         return distance;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement