给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
方法1:暴力,遍历每个元素 xx,并查找是否存在一个值与 target - x相等的目标元素。时间复杂度O(n²),空间复杂度O(1)
class Solution {
public int[] Isalike(int[] num, int t) {
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
if (num[j] == t - num[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("不存在");
}
}
public void Isalike(int[] num, int t)
{
try
{
for (int i = 0; i < num.Length; i++)
{
for (int j = i + 1; j < num.Length; j++)
{
if (num[j] == t - num[i])
{
Console.WriteLine("{0},{1}", i, j);
}
}
}
}
catch
{
Console.WriteLine("不存在");
}
}
方法二:建立哈希映射,将元素X插入表中并检查是否存在值为target-X的元素,时间、空间复杂度O(n)
class Solution {
public int[] Isalike(int[] num, int t) {
Map<Integer, Integer> m = new HashMap<>();
for (int i = 0; i < num.length; i++) {
int com= t - num[i];
if (map.containsKey(com)) {
return new int[] { map.get(com), i };
}
map.put(num[i], i);
}
throw new IllegalArgumentException("不存在");
}
}
public void Isalike(int[] num, int t)
{
Dictionary<int, int> d = new Dictionary<int, int>();
for (int i = 0; i < num.Length; i++)
{
int com = t - num[i];
if ((d.ContainsKey(com))&& (d[com] != num[i]))
{
Console.WriteLine("{0},{1}", d[com],i);
}
else if ((!d.ContainsKey(num[i]))&&(i!=num.Length-1))
{
d.Add(num[i], i);
}
else if(i==num.Length-1)
{
Console.WriteLine("不存在");
}
}
}
}