力扣算法-1
- 创业
- 2025-08-26 21:21:01

力扣算法 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 二叉树的前序遍历上一篇
js打开新标签页和关闭标签页