zoukankan      html  css  js  c++  java
  • Java找出不重复无序数组中和为n的两数的下标

     1 import java.util.HashMap;
     2 import java.util.Iterator;
     3 import java.util.Map;
     4 
     5 public class Demo5 {
     6 
     7     public static void main(String[] args) {
     8 
     9         int[] arr = new int[]{3, 4, 5, 9, 8};
    10         int num = 8;
    11         int[] ret = getIndex(arr, num);
    12         System.out.println("index of two number:" + ret[0]+" " + ret[1]);
    13 
    14     }
    15 
    16     //找到这两个数的下标,并以长度为2的数组形式返回
    17     public static int[] getIndex(int[] arr, int num){
    18         
    19         int[] ret = new int[2];   //长度为2的数组
    20         HashMap<Integer, Integer> hashMap = new HashMap<>();
    21         int index = 0;
    22         
    23         //将每个数字及其下标放入map中
    24         for (int i : arr) {
    25             hashMap.put(i, index++ );
    26         }
    27 
    28         //遍历 HashMap 并判断
    29         Iterator iterator = hashMap.entrySet().iterator();
    30         while (iterator.hasNext()){
    31             Map.Entry entry = (Map.Entry)iterator.next();
    32 
    33             int value = (int) entry.getKey();
    34             int subValue = num - value;
    35 
    36             if (hashMap.containsKey(subValue)){
    37                 //找到了
    38                 ret[0] = (int) entry.getValue();
    39                 ret[1] = hashMap.get(subValue);
    40                 break;
    41             }
    42         }
    43         return ret;
    44 
    45     }
    46 }
  • 相关阅读:
    14. HTML 列表(无序, 有序, 定义)
    13. HTML table
    12. HTML图像
    11. HTML链接
    10. HTML CSS
    learning java AWT Pannel
    learning AWT Jrame
    learning java 正则表达式
    learning java java.time相关类
    learning java Calendar类
  • 原文地址:https://www.cnblogs.com/guan-zl/p/15017564.html
Copyright © 2011-2022 走看看