主页 > 创业  > 

力扣算法-1

力扣算法-1
力扣算法 1 两数之和

给定一个整数数组nums和一个整数目标值target,请你在数组中找出和为目标值target的那两个整数,返回他们的数组下标。

(1)暴力枚举

(枚举数组每一个数x,再寻找数组中是否存在 target -x)

public int[] twoSum(int[] nums,int target) { int n = nums.length; for (int i = 0; i<n; ++i) { for(int j = i + 1; j < n;++j) { if (nums[i] + nums[j] == target) { return new int[]{i,j}; } } } return new int[0]; } (2)哈希表

对于每个x,我们查询哈希表中是否存在target-x,将x插入哈希表中

public int[] twoSum(int[] nums,int target) { Map<Integer,Integer> hashTable = new HashMap(); for(int i = 0;i<nums.length;++i) { if(hashTable.containsKey(target-nums[i])){ return new int[] {hashTable.get(target-nums[i]),i}; //返回当前x的数组索引和哈希表中匹配的数组索引值 } hashTable.put(nums[i],i); } return new in[0]; } 2 无重复字符的最长子串 3 二叉树的前序遍历
标签:

力扣算法-1由讯客互联创业栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“力扣算法-1