알고리즘/HackerRank

Jumping on the Clouds

webmaster 2021. 11. 18. 17:51
728x90

https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup 

 

Jumping on the Clouds | HackerRank

Jumping on the clouds

www.hackerrank.com

 

  • 문제
    • 문제
    • 0부터 n까지 index를 1,2 개씩 점프할 수가 있는데 1이 존재하는 곳으로는 점프를 할 수가 없다.
    • 이때, 최소한의 점프를 해서 마지막 까지 도착하는 경우중 가장 빨리 도착하는 시간을 계산해라

풀이

  • while문의 돌면서 index가 배열의 SIZE보다 작을 때 까지 돈다.
    • 경우 1 : index + 2 가 배열의 SIZE 보다 작을 경우
      • 만약 index + 2 가 1 이면 index는 index+1 , 0이면 index = index + 2
    • 경우 2 : index가 배열의 마지막 요소일 경우 탐색 - 끝까지 왔으니 break
    • 경우 3 : index가 배열의 마지막 전 요소일 경우 마지막 은 그냥 가야 되니 index + 1 해준다.
  • 
        public static int jumpingOnClouds(List<Integer> c) {
             int index = 0;//인덱스
            int answer = 0;//결과
            while(index < c.size()){ // index가 배열 크기 넘지 않을때 까지만 반복
                if(index+2 < c.size()){ // 경우 1 : index + 2 가 배열 크기보다 작을때
                    if(c.get(index+2) == 0){ // 경우 1-1 : index+2번째 요소가 0이면 2칸 점프 가능
                        index += 2;
                    }else{ //아니면 1-2 : 불가능 하므로 하나만 점프
                        index++;
                    }
                }else if(index + 1  == c.size()){ // 경우 2 : index + 1 이 배열 크기랑 같을때 , 배열을 마지막 요소를 가리킨다.
                    break;
                }else {//경우 3 : index 가 배열을 마지막 전요소를 가리키면 index는 하나 증가밖에 안된다.
                    index++;
                }
                answer++;
            }
            return answer;
        }
728x90

'알고리즘 > HackerRank' 카테고리의 다른 글

Arrays Left Rotation  (0) 2021.11.18
2D Array - DS  (0) 2021.11.18
Repeated String  (0) 2021.11.18
Counting Valleys  (0) 2021.11.18
Sales by Match  (0) 2021.11.18