My Java Solution


  • 0
    T

    Sorry I'm not a neat coder and not a good explanation presenter.

    The basic idea is to check if the last of the positions holding consecutive zeroes can be jumped over, from the places starting next to the last zero.

    The function "canJumpTwo" can be avoided. I put it there coz I first wrote everything in recursion. Too lazy to change the format.

        public static boolean canJump(int[] nums) {
    		return canJumpTwo (nums, 0, nums.length-1);
        }
    	
    	
    	public static boolean canJumpTwo (int[] nums, int i,int j){
            if (i+nums[i]>=j){
            	return true;
            }
            else{
            	if (nums[i]==0){
            		return false;
            	}
            	else{
            	boolean result = true;
            	ArrayList<Integer> list = new ArrayList<Integer>();
            	list.add(i-1);
            	for (int k= i+1; k<j;k++){
            		if (nums[k]==0 &&  nums[k+1] !=0){
            			list.add(k);
            		}
            	}
            	
            	if (nums[j]==0 && nums[j-1]==0){
            		list.add(j-1);
            	}
            	
            	for (int k= 0; k<list.size()-1;k++){
            		if(!passPosition(nums,list.get(k)+1,list.get(k+1))){
            			result =false;
            			break;
            		}
            	}
            	
            	return result;
            	}
            }
    	}
    	
    	public static boolean passPosition(int[] nums, int i, int k){
    		
    		boolean result = false;
    		
    		for (int j =i; j<k; j++){
    			if (j+nums[j]>k){
    				result=true;
    				break;
    			}
    		}
    		return result;
    	}

Log in to reply
 

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