题目1
1. 两数之和【简单】
题解1
发现自己以前刷过这题,但是用的无脑暴力解法,时间复杂度 O ( n 2 ) O(n^2) O(n2)
这次换个解法,用哈希表来做,时间复杂度 O ( n ) O(n) O(n),主要是记一下java里Map咋用
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer>hashMap=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(hashMap.containsKey(target-nums[i])){
return new int[]{hashMap.get(target-nums[i]),i};
}
hashMap.put(nums[i],i);
}
return new int[0];//创建一个容量为0的数组,即空数组(常用技巧)
}
}
题目2
69. x的平方根【简单】
题解2
二分法
求解x的平方根k,k是 k 2 < = x k^2<=x k2<=x的最大值,因此从0到x二分找k
注意0和1的特殊值处理
class Solution {
public int mySqrt(int x) {
//0和1特殊讨论
if(x==0)
return 0;
if(x==1)
return 1;
long low=0,high=x;
while(low<=high){
long mid=low+(high-low)/2;
long r=x/mid;//防止乘法溢出,改用除法
if(mid<r) low=mid+1;
else if(mid>r) high=mid-1;
else return (int)mid;
}
return (int)low-1;
}
}
牛顿迭代法
构造函数 f ( x ) = y = x 2 − C f(x)=y=x^2-C f(x)=y=x2−C
迭代公式 x i + 1 = ( 1 / 2 ) ( x i + C / x i ) x_{i+1}=(1/2)(x_i+C/x_i) xi+1=(1/2)(xi+C/xi),k次迭代后, x k x_k xk与真实值 C \sqrt{C} C足够接近,即可作为答案
class Solution {
public int mySqrt(int x) {
//0特殊讨论
if(x==0)
return 0;
double C=x,x0=x;
//迭代
while(true){
double xi=(x0+C/x0)/2;
if(Math.abs(x0-xi)<1e-7)
break;
x0=xi;
}
return (int)x0;
}
}