刷題日誌——跳躍遊戲

題目:
給定一個非負整數數組,假定你的初始位置爲數組第一個下標。

數組中的每個元素代表你在那個位置能夠跳躍的最大長度。
請確認你是否能夠跳躍到數組的最後一個下標。
例如:
A = [2,3,1,1,4],
return true.
A = [3,2,1,0,4],
return false.
格式:
第一行輸入一個正整數n,接下來的一行,輸入數組A[n]。如果能跳到最後一個下標,輸出“true”,否則輸出“false”
樣例1
輸入:

5
2 0 2 0 1
輸出:
true

解題:

法一:

採用遍歷的思想,遞歸調用,時間複雜度高,不可取。主要是從第一個數組開始,進行所有路徑的遍歷,當遍歷到最大跳躍長度爲0並且不是最後一個結點時即結束此路徑的遍歷。代碼如下(java):

import java.util.Scanner;
class Main {
	public static boolean re=false;
	public static int flag=1;
	public static void main(String args[]){
		int count,i;
		Scanner stdin = new Scanner(System.in);  
		count=stdin.nextInt();
		int []a=new int[1000];
		for(i=0;i

法二:

同樣採用遍歷的思想,遞歸調用,時間複雜度高,不可取。與法一差不多,只是從後往前遍歷。代碼如下:

import java.util.Scanner;
public class Main2 {
	public static boolean re=false;
	public static void main(String args[]){
		int count,i;
		Scanner stdin = new Scanner(System.in);  
		count=stdin.nextInt();
		int []a=new int[1000];
		for(i=0;i=i)
			{
				haha=can(index-i,a,count);
				if(haha==true)
					return true;
			}

		}
		return false;
	}

}

法三:

貪心算法,時間複雜度低,可取。主要思想就是從第一個數組元素開始計算此數組元素所能到達的最遠的數據元素下標,如果後面有更遠的則替換max值,但如果出現下標值比能達到的最遠元素max的值還大的數組元素,說明此元素不可達到,那麼最後一個元素更不可達到,就返回“false”,否則返回“true”。代碼如下(java):

import java.util.Scanner;
public class Main3 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int count,i,max=0;
		Scanner stdin = new Scanner(System.in);  
		count=stdin.nextInt();
		int []a=new int[1000];
		for(i=0;imax)
	        {
	            System.out.println("false");
	            return;
	        }
	        if(i+a[i]>max)
	            max=i+a[i];
		}
		System.out.println("true");
	}

}

法四:

不曉得什麼算法,男朋友做出來的(也是醉了)。主要思想是對數組中0值的判斷,如果數組中所有0值的數組元素可以被前面的數組元素跳過,則爲“true”,如果數組中有一個0值得數組元素不能被跳過即爲必經的數組元素,則爲“false”。代碼如下(c,有點亂):

#include

void main()
{
	int n,i,j;
	int *p;
    int *p1;
	int b=1;
    int x=0;
	scanf("%d",&n);
	p = (int *) malloc (n*sizeof(int));
	p1 = p;
	for(i=0;i1)
	{
		if(p[0]>0)
		{
			for(i=1;i=0;j--)
					{
						if(p1[j]>i-j) {x=1;break;}
					}
				    if(x==0)
				    {
                        b=0;
				    }
                    x=0;
				}
				if(b==0) {break;}
			}
		}
		if(p1[0]==0) b=0;
		if(b==0)
		{
		printf("false");
		}
		else
		{
		printf("true");
		}
	}
	else
	{
		printf("true");
	}
	
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章