题目
-
设计并实现一个 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-iii-data-structure-design
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法
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;
}
}
/**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* boolean param_2 = obj.find(value);
*/
思路
- 在类下面声明属性
- 在构造函数方法里初始化类的属性
- 在其他函数对属性和函数进行调用完成功能
下一步总结
- 类设计的原则与技巧?
- 属性权限设计的方法与技巧?