【LeetCode】刷题-esay

本文包含多个SQL查询案例,如查询大国信息、统计学生人数较多的班级等,同时还提供了多种算法解决方案,涉及二进制操作、树结构构建、字符串处理及路径判断等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

595. Big Countries


There is a table World

+-----------------+------------+------------+--------------+---------------+
| name            | continent  | area       | population   | gdp           |
+-----------------+------------+------------+--------------+---------------+
| Afghanistan     | Asia       | 652230     | 25500100     | 20343000      |
| Albania         | Europe     | 28748      | 2831741      | 12960000      |
| Algeria         | Africa     | 2381741    | 37100000     | 188681000     |
| Andorra         | Europe     | 468        | 78115        | 3712000       |
| Angola          | Africa     | 1246700    | 20609294     | 100990000     |
+-----------------+------------+------------+--------------+---------------+

A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million.

Write a SQL solution to output big countries' name, population and area.

For example, according to the above table, we should output:

//一个国家拥有大于300万平方公里的土地或者拥有超过2500万的人口,那他就是大国。

//写一个SQL语句,输出大国的名称、人口数量和面积。

//如果根据上面的表格,我们应该怎么写输出语句:


//答案:

select name, population, area from World where area>3000000 or population>25000000


input:

{"headers": {"World": ["name", "continent",	"area",	"population", "gdp"]}, "rows": {"World": [["Afghanistan", "Asia", 652230, 25500100, 20343000000], ["Albania", "Europe", 28748, 2831741, 12960000000], ["Algeria", "Africa", 2381741, 37100000, 188681000000], ["Andorra", "Europe", 468, 78115,	3712000000], ["Angola", "Africa", 1246700, 20609294, 100990000000]]}}

answer:
{"headers": ["name", "population", "area"], "values": [["Afghanistan", 25500100, 652230], ["Algeria", 37100000, 2381741]]}


201. Bitwise AND of Numbers Range

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

For example, given the range [5, 7], you should return 4.


//两个区间【m,n】0<=m<=n<=2147483647,返回在这个区间内的所有二进制和数据;

//即求m和n二进制编码中,同为1的前缀



//答案:

int count=0;

while(m!=n){

m>>=1;

n>>=1;

count++;

}

return n<<count;

笔记:

m>>=1  m转为2进制,向右边移动1位,并且赋值给m;

n<<count   左移运算 低位补0. 丢弃最高位,0补最低位,相当于左移count位就是乘以2的count次方。


654. Maximum Binary Tree

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

Construct the maximum tree by the given array and output the root node of this tree.


//找出做大的值,然后左右两边相互递归。


//答案:

class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
            return subConstructMaximumBinaryTree(nums,0,nums.length-1);

    }
    public static TreeNode subConstructMaximumBinaryTree(int[] nums,int start,int end){
        if (start > end) return null;
        int max = Integer.MIN_VALUE;
        int index = 0;
        for (int i = start; i <= end; i++){
            if (max < nums[i]){
                max = nums[i];
                index = i;
            }
        }
        TreeNode root = new TreeNode(max);
        root.left =  subConstructMaximumBinaryTree(nums,0,index-1);
        root.right =  subConstructMaximumBinaryTree(nums,index+1,end);
        return root;
    }
}


596. Classes More Than 5 Students

There is a table courses with columns: student andclass

Please list out all classes which have more than or equal to 5 students.

For example, the table:

+---------+------------+
| student | class      |
+---------+------------+
| A       | Math       |
| B       | English    |
| C       | Math       |
| D       | Biology    |
| E       | Math       |
| F       | Computer   |
| G       | Math       |
| H       | Math       |
| I       | Math       |
+---------+------------+

Should output:

+---------+
| class   |
+---------+
| Math    |
+---------+
//这是一张课程表,关于学生和班级。

//请找出有5个学生的班级。


//不知道正确错误的答案。。很迷茫这道题

select a.class from (select class,count(class) from(select distinct student,class from courses as bgroup by class having count (class)>=5)as a);


噫吁嚱,危乎高哉。

蜀道之难,难于上青天。


461. Hamming Distance


The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

答案:

class Solution {
    public int hammingDistance(int x, int y) {
          int res = x ^ y;   //二进制 x-y
        int count = 0;  
        for (int i = 0; i < 32; i++) {  
            if ((res & 1) != 0)  
                count++;  
            res >>= 1;     //往右边移一位
        }  
        return count;  
    }
}

笔记:

异或运算符,“相同出0,不同处1”。转成二进制,然后统计1的出现次数


657. Judge Route Circle

nitially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.

The move sequence is represented by a string. And each move is represent by a character. The valid robot moves areR (Right),L (Left),U (Up) andD (down). The output should be true or false representing whether the robot makes a circle.

Example 1:

Input: "UD"
Output: true

Example 2:

Input: "LL"
Output: false

机器人初始位置是(0,0),然后给机器人一个命令字符串,右(R),左(L),上(U),下(D)。机器人按照命令走完一个圈回到起点,则为true,如果没有,则为flase;

答案:

class Solution {
    public boolean judgeCircle(String moves) {
        int x=0;int y=0;
        int len=moves.size;
        if (len<=0){
            return false;
        }
        for(i;i<len;++i){
            switch(moves[i]){
                case "U":y++;break;
                case "D":y--;break;
                case "R":x++;break;
                case "L":x--;break;
            }
        }
        if(x==0&&y==0){
            return true;
        }else return false;
    }
}


3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be asubstring,"pwke" is asubsequence and not a substring.


答案:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int res=0,left=0,right=0;
        HashSet<Character> t=new HashSet<Character>();
        while(right<s.length()){
         if(!t.contains(s.charAt(right))){
             t.add(s.charAt(right++));
             res=Math.max(res,t.size());
            
         }else{
             t.remove(s.charAt(left++));
         }
            
        }
        return res;
        
 
    }
}

笔记:

Java Character类在对象中包装一个基本类型char的值;

Java String.contains()方法是包含。如果"abc".contains("a") 为true ,"abc".contains("abcd")为false,"abc".contains("d")为false;

Math.max("1","2");去两者最大的数;



198. House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
你是一个专业的强盗,计划去抢一条街上的房子。每个房子里都有一定量的钱,唯一限制你抢掉所有房子里的钱的是:相邻的房子的安保系统是连接在一起的,如果相邻的两个房子在同一晚上都被盗的话就会自动报警。

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
给出一系列非负的整数代表每个房子内的金钱数量,计算你今晚不触发报警条件的情况下可以抢到的最多的钱。

答案:

class Solution {
       public int rob(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        int[] money = new int[2];
        money[0] = 0;
        money[1] = nums[0];
        for(int i = 1; i < nums.length; i ++) {
            int temp = money[0];
            money[0] = Math.max(money[0], money[1]);
            money[1] = temp + nums[i];
        }
        return money[0] > money[1] ? money[0] : money[1];
    }
}

笔记:


213. House Robber II

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place arearranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonightwithout alerting the police.


那些房子在街头被抢劫后,小偷发现自己偷窃一个新的地方不会收到太多人注意。这一次,这里的房子都排成一个圆形,这说第一间房子和最后一间房子是邻居。

这些房子的安全系统和之前的房子是一样的。给出一个非负数的整数表,代表每个房子的钱数,确定今晚你可以抢劫的最大金额而不报警。



### LeetCode 基础语法入门教程 LeetCode 是程序员提升算法能力的重要平台之一,掌握其基础语法对于高效解至关重要。以下是关于 C++ 和 Java 的基础语法要点以及如何应用这些知识来解决 LeetCode 上的问。 #### 1. 数据类型与变量 C++ 提供了多种基本数据类型,包括但不限于 `int`、`long` 和 `double` 等[^2]。在编写程序时,应根据具体需求选择合适的数据类型以优化内存使用和计算效率。例如,在处理大规模数值运算时,推荐优先考虑浮点数或长整型以避免溢出问。 #### 2. 控制流语句 控制流是编程的核心部分,它决定了代码执行路径的选择逻辑。常用的条件分支结构如 `if...else` 或者更复杂的多路判断工具——`switch case` 可帮助开发者根据不同输入情况采取相应操作。此外还有循环机制(for/while),它们允许重复执行某段特定指令直到满足终止条件为止。 #### 3. 容器类简介及其应用场景分析 为了更好地管理和存储大量动态变化的信息单元组群对象集合体概念模型抽象表示形式即我们常说的各种标准模板库(STL)组件实例化后的实体形态表现出来的东西叫做容器(Container),其中最常用的一些包括: - **Vector**: 动态数组,支持随机访问并能在尾部快速增删元素。 - **Set & Unordered_Set**: 分别代表有序集合并具备查找功能的哈希表版本;前者按升序排列后者则不关心顺序只关注唯一性检验速度更快些时候会用到find()方法来进行成员存在性的检测工作流程简化很多哦~ - **Map & Multimap**: 键值映射关系管理利器,能够轻松实现一对一或多对一关联查询任务目标达成效果显著提高工作效率的同时也减少了错误发生的可能性几率大大降低啦!另外还有一种叫Unorderd_Map变种形式同样适用于某些特殊场合条件下呢😊 #### 4. 特殊用途的数据结构介绍 - Deque (双端队列) Deque是一种可以在两端都进行插入删除操作非常灵活方便的一种线性序列结构形式表达方式呈现出来的样子感觉特别棒👍🏻通过下面这个例子我们可以看到它是怎么被创建出来的:`Deque<Integer> deque = new LinkedList<>();` 这样我们就得到了一个基于链接列表实现原理构建而成的新对象实例可供后续进一步开发拓展之用了呀😄[^3] #### 5. 关于栈(Stacks)的知识补充说明 最后值得一提的是有关Stack方面的内容知识点分享给大家知道一下吧~原来啊,在Standard Template Library里面啊,我们的老朋友Stack其实背后隐藏着秘密武器呢🧐那就是它可以由三种不同的底层支撑技术方案任选其中之一作为实际运行环境下的物理载体介质哟😎分别是向量(Vector),双向队列(Deque)或者是简单的单链表(List)...怎么样是不是很神奇呢😉[^4] ```java // 示例:Java 中 Stack 的简单使用 import java.util.Stack; public class Main { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); // 添加元素 stack.push(10); stack.push(20); System.out.println("Top element is: " + stack.peek()); // 输出顶部元素 // 删除顶部元素 stack.pop(); System.out.println("After popping, top element is: " + stack.peek()); } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值