您的当前位置:首页正文

leetCode-01两数之和

2024-11-27 来源:个人技术集锦

问题

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:
给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

方案

方案1 map键值对

将nums所有的元素存到map中,遍历nums,查找是否存在 target-nums[i]


    public int[] twoSum1(int[] nums, int target) {

        int[] result = new int[2];

        Map<Integer, Integer> map = this.arr2Map(nums);
        for (int i = 0; i < nums.length; i++) {
            Integer numOne = nums[i];
            Integer numTwoIndex = map.get(target - numOne);
            if (numTwoIndex != null && numTwoIndex != i) {
                result[0] = i;
                result[1] = numTwoIndex;
                break;
            }
        }
        return result;

    }

    /**
     * 将nums所有的元素存到map中
     *
     * @param nums
     * @return
     */
    private Map<Integer, Integer> arr2Map(int[] nums) {

        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            Integer para = nums[i];
            map.put(para, i);
        }
        return map;
    }


方案2 map键值对

遍历nums,查找对应元素是否存在map中,不存在,则将 target- nums[i] 的值作为key存到map
举例: 2, 7, 11, 15 target=9 ,第一次读取到2,map中不存在,将 (9-2 : 0)放到map中,第二次获取7,map中存在,则找到了键值对

public int[] twoSum2(int[] nums, int target) {

      int[] result = new int[2];
      Map<Integer, Integer> map = new HashMap<>();

      for (int i = 0; i < nums.length; i++) {
          if (map.containsKey(nums[i])) {

              result[0] = map.get(nums[i]);
              result[1] = i;
              break;
          }
          map.put(target - nums[i], i);
      }
      return result;
  }

方案3:暴力匹配

两层循环,第一层从0开始,第二层从i+1开始

  public int[] twoSum3(int[] nums, int target) {
        int[] result = new int[2];
        int length = nums.length;
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {

                if (nums[i] + nums[j] == target) {
                    result[0] = nums[i];
                    result[1] = nums[j];
                    return result;
                }
            }
        }
        return result;

    }

显示全文