每日一code # 1
2021-09-15
tips:你也可以直接看leetcode本题目描述:两数之和,但建议看下面的需求描述,先知道你需要做些什么。
1.今日任务需求描述:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数,并返回它们的数组下标。
接下来,思考你会怎么实现?
class Solution {
/**
* 找出数组中和为目标值 target 的两个整数
*
* @param nums 整数数组
* @param target 目标值
* @return enum
*/
public int[] twoSum(int[] nums, int target) {
// todo
}
}
看着风景,静静的思考一下,思考很重要!!!
2.需求补充:
- 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
- 你可以按任意顺序返回答案。
3.单元测试:
tips:如果你的代码跟本文格式相同,可以拿下面单元测试进行简单测试,当然你可以补充或修改测试用例来更好的完成功能测试。
public static final int TARGET = 10;
/** 测试数组存在两个数和为target */
@Test
public void testTwoSum_exist() {
// 准备测试数据
int[] nums = new int[]{1,2,4,3,7};
// 调用方法
int[] result = Solution.twoSum(nums, TARGET);
// 校验数据
Assertions.assertEquals(2, result.length);
Assertions.assertTrue((4 == result[0] && 5 == result[1]) || (5 == result[0] && 4 == result[1]));
}
/** 测试数组不存在两个数和为target */
@Test
public void testTwoSum_notExist() {
// 准备测试数据
int[] nums = new int[]{3,2,4,5,1};
// 调用方法
int[] result = Solution.twoSum(nums, TARGET);
// 校验数据
Assertions.assertEquals(0, result.length);
}
附录:
// 实现代码(供参考)
class Solution {
/**
* 找出数组中和为目标值 target 的两个整数
*
* @param nums 整数数组
* @param target 目标值
* @return 两数的下标数组
*/
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
}
答案不唯一,语言不唯一
最后,欢迎大家一起讨论,一起进步!