給你一個整數數組 arr,請你檢查是否存在兩個整數 N 和 M,滿足 N 是 M 的兩倍(即,N = 2 * M)

給你一個整數數組 arr,請你檢查是否存在兩個整數 N 和 M,滿足 N 是 M 的兩倍(即,N = 2 * M)。
更正式地,檢查是否存在兩個下標 i 和 j 滿足:
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]

 示例 1:
 輸入:arr = [10,2,5,3]
 輸出:true
 解釋:N = 10 是 M = 5 的兩倍,即 10 = 2 * 5 。

 示例 2:
 輸入:arr = [7,1,14,11]
 輸出:true
 解釋:N = 14 是 M = 7 的兩倍,即 14 = 2 * 7 。
 示例3:
 [-2,0,10,-19,4,6,-8]

解題思路1:
1、暴力破解
2、借用輔助數組存儲原數組相應位置各元素的*2的值,然後再判斷輔助數組中是否存在位置不同但值是原數組元素的2倍的元素。

public class CheckIfExist {
  public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      System.out.println("請輸入數組: ");
      int [] nums = new int[7];
      for (int i = 0; i < nums.length; i++) {
          nums[i] = scanner.nextInt();
      }
      boolean flag  = checkIfExist(nums);
      System.out.println(flag);
  }
  
public static boolean checkIfExist(int[] arr) {
      if (arr == null){
          return false;
      }
      int [] temp = new int[arr.length];
      for (int i = 0; i < arr.length; i++) {
          temp[i] = arr[i] * 2;
      }

      for (int i = 0; i < arr.length; i++) {
          for (int j = 0; j < arr.length; j++) {
              if (temp[j] == arr[i] && (i != j)){
                  return true;
              }
          }
      }
      return false;
  }
}

解題思路2:
遍歷數組,並將數組類似字典存數組,即map<key,value>
key: 數組元素,value: 1, 然後再判斷數組元素%2 ==0 並且 map中存在2*數組元素或者數組元素/2.

 public static boolean checkIfExist1(int [] nums){
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if ((nums[i] % 2 == 0 && map.containsKey(nums[i] / 2)) || map.containsKey(nums[i] * 2)){
                return true;
            }
            map.put(nums[i],1);
        }
        return false;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章