今天开始刷leetcode 不求速度和数量,但求质量和吃透。基础差,慢慢来,比较快。
题目
解题思路
首先用暴力破解法 试一下 :
class Solution {
public int[] twoSum(int[] nums, int target) {
int a = nums.length;
for(int i=0;i<a;i++){
for(int j=i+1;j<a;j++)
{
if(nums[i]+nums[j]==target){
return new int[] {i,j};
}
}
}
return new int[0];
}
}
注意:1.java中数组的求长度 ,是 数组.length 。(而不是数组.length() )
2.因为题中要求不能同一元素使用两次 ,所以j是从i+1 开始 从0开始不对
3.创建数组的方法:int[] Array0 = new int[3]; int[] Array1 = new int[]{0,1,2};int[] Array3 = {30,31,32}; 且int[] x可以变成int x[], 注意格式 。
第二种方法 :哈希表的方法
思路:创建一个哈希表,哈希表存储的是键值对,把数组和其每个元素对应的 坐标存储成键值对的方式,例如nums={2,7,15,6} 那么map为<2,0>,<7,1>,<15,2>,<6,3>. 首先 创建哈希表时,哈希表为空,这时候遍历数组 ,查询哈希表中是否存在【target-元素值】这一个键值对,如果没有,就添加当前元素的值和坐标这一键值对, 如果有的话,则肯定之前已经存储过【target-元素值】这一键值对,那么找到了这个解,返回【target-元素值】这一个键的值(也就是对应的数组中的坐标)和当前遍历的i即可
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
int[] res = new int[2];
for (int i = 0;i<nums.length;i++)
{
int other = target-nums[i];
if (map.get(other) != null){
res[0]=map.get(other);
res[1]=i;
return res;
}
map.put(nums[i],i);
}
return res;
}
}
注意:1.创建哈希表的方式是Map<Integer,Integer> map = new HashMap<>();
2. Map中的方法需要记一下,根据键查找值 :map.get(键) 返回的是值,添加键值对 map.put(键,值)
3.如果要在idea 中练习,在主函数中调用方法,需要创建一个当前类的对象 ,再用 对象.方法 来调用方法。
方法3:排序+双指针的方法。
思路:将这个数组按从小到大排序生成一个新的数组up,之后设置两个指针,一个在头为i,一个在尾为 j,遍历,当up[i]+up[j] <target时,i++,当up[i]+up[j] > target时,j--,当等于时,将这两个值记录下来,再从sums数组中遍历两次查找这两个值对应的坐标,判断条件时要加上两个坐标不能相同(值可以相同,坐标不能相同)。
class Solution {
public int[] twoSum(int[] nums, int target) {
int f=0,l=0,k;
int[] res = new int[2];
int[] up = new int[nums.length];
System.arraycopy(nums,0,up,0,nums.length);
Arrays.sort(up);
for(int i=0,j=nums.length-1;i<j;)
{
if(up[i]+up[j]>target){
j--;
}
else if(up[i]+up[j]<target){
i++;
}
else if(up[i]+up[j]==target){
f=up[i];
l=up[j];
break;
}
}
for( k=0;k<nums.length;k++){
if(nums[k]==f){
res[0]=k;
break;
}
}
for(int i=0;i<nums.length;i++){
if (nums[i]==l && i!=k){
res[1]=i;
}
}
return res;
}
}
注意:1.复制数组用System.arraycopy(源数组,首元素坐标,目的数组,首元素坐标 ,复制长度)
2.从小到大排序算法是Arrays.sort(数组) 时间复杂度是nlogn;
3,注意一点,先定义一个变量不赋值,后面if的条件里进行赋值了,再跳出条件使用这个变量的值时,会提示这个变量没赋值, 所以遇到这种情况,要尽量在定义时赋值,哪怕赋值成0 也好。
文章仅供自己学习使用,不足之处,欢迎指正。