题解 | 两数之和

两数之和

https://www.nowcoder.com/practice/c4a4f030ca374d9bb9df5c0bdf388626

using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param nums int整型一维数组
     * @param target int整型
     * @return int整型一维数组
     */
    public List<int> twoSum (List<int> nums, int target) {
        //hashi表找补
        //数值,下标
        Dictionary<int, int> hashset=new Dictionary<int, int>();

        List<int> res = new List<int>();
        for(int i=0;i<nums.Count;i++){
            //补 
            int tmp = target - nums[i];
            if(hashset.ContainsKey(tmp)){
                int tmpres = hashset[tmp]+1;
                res.Add(tmpres);
                res.Add(i+1);

                return res;
            }else{
                hashset.Add(nums[i], i);
            }
        }
       
       return res;
       
        //暴力
        // List<int> res =new List<int>();
        // for(int i=0;i<nums.Count;i++){

        //     for(int j=i+1;j<nums.Count;j++){
        //         if((nums[i]+nums[j])==target){
        //             res.Add(i+1);
        //             res.Add(j+1);
        //             break;
        //         }
        //     }
        // }
        // return res;

    }
}

全部评论

相关推荐

03-23 15:00
已编辑
厦门大学 Java
xiaowl:你这个简历的问题是对于技术点、项目的描述,都是描述action的,对于面试官而言,仅能知道你干了什么,无法判断你为什么这么干,干的好不好。
点赞 评论 收藏
分享
caicaidog:现实里没实习的还是占多数的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务