算法:两数之和
13122256420
664
2024-02-26
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。
  • nums = [2,7,11,15]
  • key = 9
  • 输出:[0,1]


js版本

tow_sum()

function tow_sum() {
    let arr = [5, 8, 7, 6,2, 10]
    let key = 9

    let res = []
    let obj = {}

    for (let i = 0; i < arr.length; i++) {
        let result = key - arr[i]
        console.log(obj[result], result, obj)
        if (obj[result] === 0 || obj[result]) {
            res = [obj[result], i]
        }
        obj[arr[i]] = i
    }

    console.log(res)
}

go版本

func tow_sum() {
	var key = 9
	var arr = []int{5, 8, 7, 6, 2, 10}

	var res []int
	var obj = make(map[int]int)

	for i := 0; i < len(arr); i++ {
		var result = key - arr[i]

		if _, ok := obj[result]; ok {
			res = append(res, obj[result])
			res = append(res, i)
		}
		fmt.Println(arr[i], "==")
		obj[arr[i]] = i
	}
	fmt.Println(res)

}

rust版本

fn tow_sum() {
    let arr = vec![5, 8, 7, 6, 2, 10];
    let key = 9;

    let mut obj: HashMap<i32, i32> = Default::default();
    let mut res: Vec<i32> = vec![];

    for i in 0..arr.len() {
        let result = key - arr[i];
        if obj.contains_key(&result) {
            println!("进来啦");
            let a = obj[&result];
            res.push(a);
            res.push(i as i32);
        }
        obj.insert(arr[i], i as i32);
    }

    println!("{:?} ----- ", res);
}