[LeetCode]Two Sum

本文介绍了两种解决“两数之和”问题的算法实现方案。一种是使用哈希表来存储数组元素及其索引,从而快速查找目标值的配对元素;另一种是通过排序并采用夹逼法来寻找配对元素,适用于有序数组的情况。此外,还提供了一个接口设计,用于存储输入值并测试是否存在两个数相加等于给定值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer, Integer> num = new HashMap();
        for(int i = 0; i < numbers.length; i++) {
            num.put(numbers[i], i);
        }
        for(int i = 0; i < numbers.length; i++) {
            //try to see if the difference is in the hashmap
            Integer index2 =  num.get(target - numbers[i]);
            if(index2 != null && index2 != i) {
                //only add 1 here if the array is designed strangely
                return new int[] {i+1, index2+1};
            }
        }
        return null;
    }
}

另一种,design an interface for it.

题目:

public interface TwoSum {
 /**
  * Stores @param input in an internal data structure.
  */
 void store(int input);

 /**
  * Returns true if there is any pair of numbers in the internal data structure
  * which have sum @param val, and false otherwise.
  * For example, if the numbers 1, -2, 3, and 6 had been stored,
  * the method should return true for 4, -1, and 9, but false for 10, 5, and 0
  */
 boolean test(int val);
}

解答(用的是夹逼法)

public class TwoSumImpl implements TwoSum {  
 private List<Integer> array;
 public TwoSumImpl() {
   this.array = new ArrayList<Integer>();
 }
 @Override
 public void store(int input) {
   array.add(input);
 }
 @Override
 public boolean test(int val) {
   Collections.sort(array);         // O(nlogn)
   int i = 0, j = array.size()-1;
   while (i < j) {
     if (array.get(i) + array.get(j) == val) return true;
     else if (array.get(i) + array.get(j) < val) ++i;
     else ++j;
   }
   return false;
 }
}

follow-up: to optimize the performance, we can use a cache for caching the previously computed results.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值