阿里2015筆試附加題-一個數組中存在一組數字,其中有一個數字重複3遍,其他2遍,在O(1)空間找到那個重複3次的數


題目就如標題,還要求時間儘可能短。這一題類似於LeetCode上的SingleNum那題,思路是將所有數字進行異或操作,最後剩下的那個數字就是重複3遍的。


代碼如下:

package test2;

public class test2 {

	public static int getNum(int[] array){
        
        int result = 0;
        for(int i = 0; i < array.length;i ++){
          result ^= array[i];
        }
        return result;
      
      }
	
	public static void main(String[] args){
		int[] array = {88, 459, 5262, 88, -17, 677, 88, 677, -17, 459, 5262};
		System.out.print(getNum(array));
	}
}


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