NK: sum of two numbers (C#)

Given an integer array numbers and a target value target, please find two subscripts in the array that add up to the target value. The returned subscripts are arranged in ascending order.

(Note: The returned array subscript starts from 1, ensuring that the target can be obtained by adding the two numbers in the array)

Example 1

enter:

[3,2,4],6

return value:

[2,3]

illustrate:

Because 2+4=6, and the subscript of 2 is 2, and the subscript of 4 is 3, and because subscript 2 < subscript 3, it returns [2,3]            

Example 2

enter:

[20,70,110,150],90

return value:

[1,2]

illustrate:

20+70=90     
using System;
using System.Collections;//hashTable路径
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param numbers int整型一维数组
     * @param target int整型
     * @return int整型一维数组
     */
    public List<int> twoSum (List<int> numbers, int target) {
        List<int> list = new List<int>();//创建输出列表为空
        Hashtable hash = new Hashtable();//hash表存储遍历数据
        for(int i=0; i<numbers.Count;i++){
            //开始遍历数组中的元素
            //计算差值,如果遍历数组元素时,hash表中存在差值,返回结果对应的索引值,否则将该数组元素放入hash表中
            //目标值与遍历数组元素的差值,键存放差值,值存放对应的i索引值
            int d = target - numbers[i];//差值
            if(hash.ContainsKey(d)){
                list.Add((int)hash[d]+1);//获取hash的值,也就是下标(记得转int),+1是因为从1开始计数
                list.Add(i+1);//数组元素i
            }else if(!hash.Contains(numbers[i])){
                //判断hash表中是否已存入该元素,键不能重复
                hash.Add(numbers[i], i);//将遍历数组元素存入hash表中
            }
        }
        return list;//list defalt升序排列
    }
}

Guess you like

Origin blog.csdn.net/qq_43801336/article/details/129955236