【面试】基本算法


这里记录面试时遇到的一些算问题,都是很基础的,基础的不能再基础了,脑子不好,记录下来。


排序一:

-(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);
	}


你可能感兴趣的:(算法,面试)