【面試】基本算法


這裏記錄面試時遇到的一些算問題,都是很基礎的,基礎的不能再基礎了,腦子不好,記錄下來。


排序一:

-(void) doDesc{

    
    int list[12] = {12,42,21,45,6,13,89,23,48,74,3,32};
    

    for (int i=0; i<=11; i++) {
       
        
        
        for (int j=11; j>i; j--) {
            
            //從大到小
//            if (list[j]>list[j-1]) {
//                int temp =list[j];
//                list[j] = list[j-1];
//                list[j-1] = temp;
//                
//            }
            //從小到大
            
            if (list[j]<list[j-1]) {
                int temp = list[j-1];
                list[j-1] = list[j];
                list[j] = temp;
            }
            
            
            
        }
 
    }
    
    for (int k =0 ; k<12; k++) {
        NSLog(@"%d == %d",k,list[k]);

    }
    
    
}

排序二:

	/**
	 * 按照從小到大或從大到小排序
	 */
	public static void desc() {

		int[] as = { 21, 23, 45, 6, 26, 74, 11, 22, 90, 48, 32, 64, 43, 67 };

		for (int i = 0; i < as.length; i++) {

			for (int j = 0; j < as.length - 1; j++) {
				// 從小到大 從大到小:as[j] < as[j + 1]
				if (as[j] > as[j + 1]) {
					int stamp = as[j];
					as[j] = as[j + 1];
					as[j + 1] = stamp;
				}

			}
		}

		for (int i = 0; i < as.length; i++) {
			System.out.println("as result:" + as[i]);
		}

	}

找相同值

	/**
	 * 返回數組中相同的值
	 */
	public static void getSame() {
		int[] as = { 21, 22, 45, 6, 26, 74, 11, 22, 90, 67, 32, 64, 43, 67 };
		for (int i = 0; i < as.length; i++) {
			for (int j = i; j < as.length - 1; j++) {
				if (as[i] == as[j + 1]) {
					System.out.println("same number is :" + as[i]);
				}

			}
		}
	}

try catch

	/**
	 * 考察try catch finally 中帶return
	 * 
	 * @param str
	 * @return
	 */
	@SuppressWarnings("finally")
	public static String getStr(List<String> str) {
		try {
			str.add("aa");
			return "a";
		} catch (Exception e) {
			str.add("bb");
			return "b";
		} finally {
			str.add("cc");
			return "c";
		}

	}

句子以某種分割倒過來輸出

	/**
	 * 句子倒過來輸出
	 */
	public static void sentenceReback() {
		String s = "I love play this game";
		String[] result = s.split(" ");
		StringBuffer sb = new StringBuffer();
		for (int i = result.length - 1; i >= 0; i--) {
			sb.append(result[i]);
			sb.append(" ");
		}
		System.out.println("reback is :" + sb);
	}


發佈了95 篇原創文章 · 獲贊 123 · 訪問量 486萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章