​LeetCode刷题实战170:两数之和 III - 数据结构设计

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 两数之和 III - 数据结构设计  ,我们先来看题面:

https://leetcode-cn.com/problems/two-sum-iii-data-structure-design/

Design and implement a TwoSum class. It should support the following operations: add
and find.
add(input) – Add the number input to an internal data structure.
find(value) – Find if there exists any pair of numbers which sum is equal to the value.

题意

设计并实现一个 TwoSum 的类,使该类需要支持 add 和 find 的操作。

add 操作 - 对内部数据结构增加一个数。

find 操作 - 寻找内部数据结构中是否存在一对整数,使得两数之和与给定的数相等。

样例

示例 1:

add(1); add(3); add(5);
find(4) -> true
find(7) -> false

示例 2:

add(3); add(1); add(2);
find(3) -> true
find(6) -> false

解题

  • 在类下面声明属性

  • 在构造函数方法里初始化类的属性

  • 在其他函数对属性和函数进行调用完成功能

class TwoSum {
        //属性
        private ArrayList<Integer> nums;
        private boolean is_sorted;
    /** Initialize your data structure here. */
    public TwoSum(){
        this.nums = new ArrayList<Integer>();
        is_sorted =false;
    } 
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        this.nums.add(number);
        this.is_sorted = false;

    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
         if (!this.is_sorted) {
      //调用Collections类进行数组排序
      Collections.sort(this.nums);
    }
    int low = 0, high = this.nums.size() - 1;
    while (low < high) {
      int twosum = this.nums.get(low) + this.nums.get(high);
      if (twosum < value)
        low += 1;
      else if (twosum > value)
        high -= 1;
      else
        return true;
    }
    //默认返回false
    return false;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-160题汇总,希望对你有点帮助!

LeetCode刷题实战161:相隔为1的编辑距离

LeetCode刷题实战162:寻找峰值

LeetCode刷题实战163:缺失的区间

LeetCode刷题实战164:最大间距

LeetCode刷题实战165:比较版本号

LeetCode刷题实战166:分数到小数

LeetCode刷题实战167:两数之和 II - 输入有序数组

LeetCode刷题实战168:Excel表列名称

LeetCode刷题实战169:多数元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程IT圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值