陌陌面试算法频率
递归:
return 1 / (x * myPow(x, - n - 1));含义:return 1/(myPow(x,-n)) 或者 return myPow(1/x,-n)会出现错误
错误原因未知
class Solution {
public double myPow(double x, int n) {
if(n == 0){
return 1;
}else if(n < 0){
return 1 / (x * myPow(x, - n - 1));
}else if(n % 2 == 1){
return x * myPow(x, n - 1);
}else{
return myPow(x * x, n / 2);
}
}
}
注意指针变换条件
当height[l]<height[r]时,只能移动较小的,因为移动较大的一个只会导致area越来越小,因为area由小的决定,r-l减小。只能希望高度增加。所以通过移动小的来增加高度,才可能得到的较大的面积
class Solution {
public int maxArea(int[] height) {
int l=0, r=height.length-1;
int ans = 0;
while(l<r){
int area = Math.min(height[l],height[r])*(r-l);
ans = Math.max(area,ans);
if(height[l]<height[r]) l++;
else r--;
}
return ans;
}
}
思路:HashMap用来存储数值和索引,因为他只有两个值,所以不需要回溯算法
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hash = new HashMap<>();
for(int i=0; i<nums.length; i++){
if(hash.containsKey(target-nums[i])){
return new int[] {hash.get(target-nums[i]),i};
}
hash.put(nums[i],i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
class Solution {
public int strToInt(String str) {
char[] ch = str.trim().toCharArray();
int len = ch.length;
if(len==0||str.length()==0||str==null){
return 0;
}
int i=0;
int sign = 1;
int ret = 0;
if(ch[0]=='-'){
sign = -1;
i = 1;
}
int bdny = Integer.MAX_VALUE/10;
if(ch[0]=='+'){
i = 1;
}
for(int j=i; j<len; j++){
if(ch[j]<'0'||ch[j]>'9'){
break;
}
if(ret>bdny||(ret==bdny&&ch[j]>'7')){
return sign>0?Integer.MAX_VALUE:Integer.MIN_VALUE;
}
ret = ret*10+ch[j]-'0';
}
return sign*ret;
}
}