题解 | #两数之和#
两数之和
https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
using System;
using System.Collections;
using System.Collections.Generic;
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public List<int> twoSum (List<int> numbers, int target) {
// write code here
if (numbers.Count == 2) return new List<int>() {
1, 2
};
if (numbers.Count == 2) return new List<int>() {
1, 2
};
List<int> res = new List<int>();
Dictionary<int, int> dic = new Dictionary<int, int>();
for (int i = 0; i < numbers.Count; i++) {
int temp = target - numbers[i];
if (dic.ContainsKey(temp)) {
res.Add(i + 1);
res.Add(dic[temp] + 1);
} else {
if (!dic.ContainsKey(numbers[i])) dic.Add(numbers[i], i);
}
}
res.Sort();
return res;
}
}

美团成长空间 2667人发布
查看5道真题和解析