怒刷leetcode题目(2)235,191,141,217,

本文详细介绍了在数据结构中处理二叉搜索树、位运算解决计数1比特问题以及链表循环检测的算法。通过实例分析,解释了如何在不同的场景下应用这些经典算法,包括寻找最低公共祖先、计算二进制位数以及判断链表是否有环。文章旨在为程序员提供实用的解决方案和深入的理解。

235 Lowest Common Ancestor of a Binary Search Tree 38.6% Easy

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    if(root==NULL || p==NULL || q==NULL){
        return false;
    }
    if(p->val<root->val &&q->val<root->val ){
        return lowestCommonAncestor(root->left, p,q);
    }else if(p->val>root->val &&q->val>root->val){
        return lowestCommonAncestor(root->right, p,q);
    }else if(p->val == root->val ||q->val == root->val){
        return root;
    }else{
        return root;
    }
}
首先大家必须了解BST的特点,若两个节点都在根节点的同一侧,就可以将那一侧的子树拿出来做递归,直到遇到根节点是其中一个节点,返回该节点。或者两点分别在节点的两侧,返回该节点。


191 Number of 1 Bits 37.6% Easy

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

int hammingWeight(uint32_t n) {
    int count= 0;
    while(n!=0){
        n = n & (n-1);
        count++;
    }
    return count;
}
n-1可以将最右的1变成0,右方的0全部变成1。

例如:1011011000会变成1011010111

将n&(n-1)可以将最右边的0去掉,重复就可以将n变成0,记录次数,返回次数即可


141 Linked List Cycle 36.3% Medium

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    if(head==NULL){
        return false;
    }
    struct ListNode *pointer1 = head;
    struct ListNode *pointer2 = head;
    while(pointer2!=NULL && pointer2->next!=NULL){
        pointer1 = pointer1->next;
        pointer2 = pointer2->next->next;
        if(pointer1 == pointer2){
            return true;
        }
    }
    return false;
}


使用快慢指针,快指针一次走两步,慢指针一次走一步,如果运行之后相遇,则是有循环


217 Contains Duplicate 36.0% Easy
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

bool containsDuplicate(int* nums, int numsSize) {
    if(nums==NULL||numsSize<2){
        return false;
    }
    for(int i = 0; i<numsSize;i++){
        for(int j=i+1;j<numsSize;j++){
            if(nums[i]==nums[j]){
                return true;
            }
        }
    }
    return false;
}

这个方法不是最好的,看tags提醒这道题应该用hashtable做,不过c没有现成的hashtable,不知道该怎么实现,请大神们指教。


### 在 IntelliJ IDEA 中练习 LeetCode 编程题 IntelliJ IDEA 是一个功能强大的 Java 开发环境,通过使用插件可以方便地在本地 IDE 中直接练习 LeetCode 编程题。以下是详细的配置和使用方法。 #### 1. 安装 LeetCode 插件 首先,需要在 IntelliJ IDEA 中安装 LeetCode 揖件: 1. 打开 IntelliJ IDEA,进入 **Settings (设置)**(快捷键为 `Ctrl + Alt + S`)。 2. 在左侧菜单中选择 **Plugins (插件)**。 3. 在搜索框中输入 `LeetCode`。 4. 找到由社区开发的 LeetCode 插件,点击 **Install (安装)**。 5. 安装完成后重启 IntelliJ IDEA [^2]。 #### 2. 配置 LeetCode 插件 安装插件后,需要进行一些基本配置,以便插件能够正确连接到 LeetCode 账户并下载题目: 1. 重启 IntelliJ IDEA 后,在左侧边栏会看到一个 **LeetCode** 图标,点击它。 2. 点击登录按钮,进入 LeetCode 登录页面。 3. 在浏览器中打开 [LeetCode 网站](https://leetcode.com/),并登录你的账户。 4. 打开浏览器的开发者工具(通常可以通过按 `F12` 或 `Ctrl + Shift + I` 打开),在 **Application** 或 **Storage** 标签下找到 `LEETCODE_SESSION` 的 Cookie 值。 5. 将 Cookie 值复制并粘贴到 IntelliJ IDEA 插件的登录框中,完成登录 [^2]。 #### 3. 下载并练习 LeetCode 题目 登录成功后,可以在插件中浏览 LeetCode 上的所有题目,并选择相应的题目进行练习: 1. 在左侧边栏的 LeetCode 插件界面中,可以看到题目列表。 2. 右键点击某个题目,选择 **Show Problem (显示题目)**,插件会在右侧显示题目的详细描述。 3. 再次右键点击题目,选择 **Generate File (生成文件)**,插件会自动生成一个包含题目描述和类框架的 Java 文件。 4. 在生成的 Java 文件中编写代码,并使用插件提供的功能进行测试和调试 [^3]。 #### 4. 本地调试与测试 IntelliJ IDEA 提供了强大的调试功能,可以在本地对 LeetCode 题目进行调试: 1. 在代码编辑器中设置断点。 2. 右键点击代码编辑器中的类或方法,选择 **Debug (调试)**。 3. 插件会自动运行测试用例,并在断点处暂停,方便查看变量值和程序执行流程 [^3]。 #### 5. 提交代码 完成题目后,可以直接通过插件将代码提交到 LeetCode: 1. 在代码编辑器中右键点击,选择 **Submit (提交)**。 2. 插件会将代码提交到 LeetCode,并在插件界面中显示提交结果 [^1]。 #### 6. 代码保存与管理 IntelliJ IDEA 提供了强大的项目管理功能,可以方便地保存和管理 LeetCode 题目的代码: 1. 每道题目的代码都会保存在一个独立的文件中,文件名通常包含题目编号和题目名称。 2. 可以通过版本控制系统(如 Git)将代码保存到远程仓库中,方便后续查阅和复习 [^1]。 ### 示例代码 以下是一个简单的 LeetCode 题目示例代码,展示了如何在 IntelliJ IDEA 中编写和测试代码: ```java public class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[] {i, j}; } } } throw new IllegalArgumentException("No two sum solution"); } public static void main(String[] args) { Solution solution = new Solution(); int[] nums = {2, 7, 11, 15}; int target = 9; int[] result = solution.twoSum(nums, target); System.out.println("Result: [" + result[0] + ", " + result[1] + "]"); } } ``` 在 IntelliJ IDEA 中运行 `main` 方法,可以测试 `twoSum` 方法的正确性,并查看输出结果 [^3]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值