leetcode算法题解(Java版)-5-简单模拟,字符串处理

简介: 因为题目还是很简单,不考虑将装水的容器倾斜,所以只要考虑梯形中最短的边和底边的乘积就行了:正反两遍循环数组,第一遍从0~len,先固定最左边的边,从右往左遍历数组,如果碰到大于等于最左边边长的边,那就判断是否大于当前的最大盛水体积并跟新,然后就停止这次循环,将最左边的边向右移动一格,重复操作;第二遍从len~0,和第一遍一样。

一、简单贪心

题目描述

Given n non-negative integers a1 , a2 , ..., an , where each represents a point at coordinate (i, ai ). n vertical lines are drawn such that the two endpoints of line i is at (i, ai ) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.

思路

  • 这题在一分钟内就想了个笨方法,迅速敲完,KO!
  • 因为题目还是很简单,不考虑将装水的容器倾斜,所以只要考虑梯形中最短的边和底边的乘积就行了:正反两遍循环数组,第一遍从0~len,先固定最左边的边,从右往左遍历数组,如果碰到大于等于最左边边长的边,那就判断是否大于当前的最大盛水体积并跟新,然后就停止这次循环,将最左边的边向右移动一格,重复操作;第二遍从len~0,和第一遍一样。

代码

public class Solution {
    public int maxArea(int[] height) {
        int len=height.length;
        if(len==0){
            return 0;
        }
        int maxW=0;
        for(int i=0;i<len;i++){
            for(int j=len-1;j>i;j--){
                if(height[j]>=height[i]){
                    if(height[i]*(j-i)>maxW){
                        maxW=height[i]*(j-i);
                    }
                    break;
                }
            }
        }
        for(int i=len-1;i>0;i--){
            for(int j=0;j<i;j++){
                if(height[j]>=height[i]){
                    if(height[i]*(i-j)>maxW){
                        maxW=height[i]*(i-j);
                    }
                    break;
                }
            }
        }
        return maxW;
    }
}

思路2

  • 好吧,虚心学习,看了一下其他人的代码。发现一个好方法:
  • 从两边往中间走,每次舍弃较短的边,因为宽度减小,要通过高度的增加来弥补

代码

public class Solution {
    public int maxArea(int[] height) {
        int len=height.length;
        if(len==0){
            return 0;
        }
        int l=0;
        int r=len-1;
        int maxW=0;
        while(l<r){
            maxW=Math.max(maxW,Math.min(height[l],height[r])*(r-l));
            if(height[l]<height[r]){
                l++;
            }
            else{
                r--;
            }
        }
        return maxW;
    }
}

二、简单回文数字

题目描述

Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.

思路

  • 题目有个限制,就是不能开辟新的空间。
  • 那就和一般的回文串做法不同了,可以这么来搞:干脆求出它翻转过来的整型,最后比较是否值相等。
  • 想到这个思路,是因为int型的特殊基本数据类型,特别对待,哈哈哈

代码

public class Solution {
    public boolean isPalindrome(int x) {
        if(x<0){
            return false;
        }
        int reverse=0;
        int x_rel=x;
        while(x!=0){
            reverse=reverse*10+x%10;
            x/=10;
        }
        return  reverse==x_rel;
    }
}

三、字符串,模拟

题目描述
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
spoilers alert... click to show requirements for atoi.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
思路

  • 细节要求比较多,正负号,非法字符,溢出等都要考虑。

代码

public class Solution {
    public int atoi(String str) {
        if(str==null||str.length()==0){
            return 0;
        }
        int pos=0;
        while(str.charAt(pos)==' '){
            pos++;
        }
        int flag=1;
        if(str.charAt(pos)=='-'){
            flag=-1;
            pos++;
        }
        if(str.charAt(pos)=='+'){
            flag=1;
            pos++;
        }
        int len=str.length();
        int res=0;
        for(int i=pos;i<len;i++){
            char c=str.charAt(i);
            if(c<'0'||c>'9'){
                break;
            }
            if(res>Integer.MAX_VALUE/10||(res==Integer.MAX_VALUE/10&&c>'7')){
                if(flag>0){
                    return Integer.MAX_VALUE;
                }
                else{
                    return Integer.MIN_VALUE;
                }
            }
            res=res*10+(c-'0');
        }
        return res*flag;
    }
}
目录
相关文章
|
29天前
|
算法 Java C语言
C++和Java中的随机函数你玩明白了吗?内附LeetCode470.rand7()爆改rand10()巨详细题解,带你打败LeetCode%99选手
C++和Java中的随机函数你玩明白了吗?内附LeetCode470.rand7()爆改rand10()巨详细题解,带你打败LeetCode%99选手
|
10天前
|
算法 安全 Java
性能工具之 JMeter 自定义 Java Sampler 支持国密 SM2 算法
【4月更文挑战第28天】性能工具之 JMeter 自定义 Java Sampler 支持国密 SM2 算法
25 1
性能工具之 JMeter 自定义 Java Sampler 支持国密 SM2 算法
|
4天前
|
存储 算法
Leetcode 30天高效刷数据结构和算法 Day1 两数之和 —— 无序数组
给定一个无序整数数组和目标值,找出数组中和为目标值的两个数的下标。要求不重复且可按任意顺序返回。示例:输入nums = [2,7,11,15], target = 9,输出[0,1]。暴力解法时间复杂度O(n²),优化解法利用哈希表实现,时间复杂度O(n)。
16 0
|
16天前
|
设计模式 算法 Java
[设计模式Java实现附plantuml源码~行为型]定义算法的框架——模板方法模式
[设计模式Java实现附plantuml源码~行为型]定义算法的框架——模板方法模式
|
16天前
|
搜索推荐 算法 Java
Java实现的常用八种排序算法
提到数据结构与算法,无法避免的一点就包含排序,熟练的掌握各种排序算法则是一个程序员必备的素质之一,除此之外,排序算法也是当下各大技术公司比较喜欢问的技术点,所以,就这一点JavaBuild整理了常见的8种排序算法
6 0
|
21天前
|
机器学习/深度学习 数据采集 算法
使用 Java 实现机器学习算法
【4月更文挑战第19天】Java在数据驱动时代为机器学习提供支持,具备丰富的数学和数据结构库,适用于实现线性回归、决策树、SVM和随机森林等算法。实现时注意数据预处理、模型选择、评估指标和可视化。利用Java的库和编程能力可构建高效模型,但需按问题需求选择合适技术和优化方法。
|
21天前
|
算法
代码随想录算法训练营第六十天 | LeetCode 84. 柱状图中最大的矩形
代码随想录算法训练营第六十天 | LeetCode 84. 柱状图中最大的矩形
20 3
|
21天前
|
存储 算法
代码随想录算法训练营第五十九天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
代码随想录算法训练营第五十九天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
22 1
|
21天前
|
算法
代码随想录算法训练营第五十七天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
代码随想录算法训练营第五十七天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
18 3
|
21天前
|
算法
代码随想录算法训练营第五十六天 | LeetCode 647. 回文子串、516. 最长回文子序列、动态规划总结
代码随想录算法训练营第五十六天 | LeetCode 647. 回文子串、516. 最长回文子序列、动态规划总结
34 1