劍指offer變體-找出數組裏只出現一次的數字,返回該數字的下標-Java

一個整型數組裏除了兩個數字之外,其他的數字都出現了兩次。

請寫程序找出這兩個只出現一次的數字,返回該數字的下標。

這個題以前寫過,鏈接在這裏,以前是返回一個值,這次是返回一個下標

(開數組的思想也可以返回數的值,return的時候)。

思路變了,這次開數組的思想來做,找到數組裏面的max值,開一個max大小的int數組。

 

import java.util.Collections;
import java.util.Arrays;
public class OnceNum{
    // 輸入一個數組,
    public static void main(String[] args) {
        int [] nums = {7,9,5,7,256,9,5};
        int i = findOnceNum(nums);
        System.out.println(i);
     }
     public static int findOnceNum(int[] nums){
         if(nums.length == 0){
             return -1;
         }
         //int max = (int)Collections.min(Arrays.asList(nums));  //此時nums爲Integer時可以
         int max = Arrays.stream(nums).max().getAsInt(); //求最大值
         int[] res = new int[max + 1];  //通過new方式簡歷的int[]數組的初始值是0,這裏最大值要+1,不然會越界。
         for(int i = 0; i <nums.length; i++){
             res[nums[i]] ++;
         }
         for(int j = 0; j < nums.length; j++){
             if(res[nums[j]] == 1){
                 return j;
             }
         }
         return -1;
     }
}

 

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