力扣算法-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 + nums == target) {
return new int[]{i,j};
}
}
}
return new int;
}
(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)){
return new int[] {hashTable.get(target-nums),i}; //返回当前x的数组索引和哈希表中匹配的数组索引值
}
hashTable.put(nums,i);
}
return new in;
}
2 无重复字符的最长子串
3 二叉树的前序遍历
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]