【LeetCode】Agorithms 题集(一)

Single Number

题目

Given an array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

思路:

为了满足时间和空间复杂度,必须利用异或的性质。

异或: 1 XOR 1 = 0     0 XOR 0 = 0     1 XOR 0 = 1    0 XOR 1 = 1      即同样为 0。不同为1

依据异或性质,有例如以下等式: 对随意整数。a b c ,  a XOR a = 0    a XOR b XOR a = b

即随意两个同样的数异或一定得 0, 若是一堆数,除了一个数,其它都是成对出现,则将全部数异或起来,剩下的就是我们要找的数。

复杂度为 O(n)

代码:
class Solution{
public:
    int singleNumber(int A[], int n) {
        int ans;
        for(int i = 0; i < n;++i)
            ans ^= A[i];
        return ans;
    }
};

Maximum Depth of Binary Tree

题目

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

思路

简单递归的考查,求一棵树的深度。仅仅要在左子树和右子树中取最大高度加 1 就是根的高度,递归下去即可。

代码
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(root == NULL) return 0;

        int ans = 1;
        int l = maxDepth(root->left);
        int r = maxDepth(root->right);

        ans += max(l,r);

        return ans;
    }
};

Same Tree

题目:

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

思路:

考察递归。

推断两棵树相等,仅仅要递归推断两棵树的结构和值。所以遇到一个指针为空的时候,还有一个指针一定要为空。不为空的时候,两个指针的值必须相等。

再递归左右子树是否相等。

代码:
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q) {
		bool flag = true;

		/* 当中一个为空,则肯定结束 */
		if(p == NULL || q == NULL)
		{
			/* 两个都为空才是相等的 */
			if(p == NULL && q == NULL)
				return true;
			return false;
		}

		/* 两个节点的值不等则 false */
		if(p->val != q->val) return false;

		/* 递归推断左子树 */
		flag = flag & isSameTree(p->left,q->left);

		/* 递归推断右子树 */
		flag = flag & isSameTree(p->right,q->right);

		return flag;
    }
};

Reverse Integer

题意:

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

思路:

把整数倒转。非常easy。仅仅要先推断是否负数,存起来。

之后取绝对值,把绝对值倒转后再决定是否是负数。

代码:
class Solution {
public:
    int reverse(int x) {
		bool neg = (x < 0);

		x = abs(x);

		int ans = 0;

		while(x)
		{
			int t = x%10;
			ans = ans*10 + t;
			x = x/10;
		}

		if(neg) ans = -ans;

		return ans;
    }
};

Binary Tree Preorder Traversal

题意:

Given a binary tree, return the preorder traversal of its nodes‘ values.

For example:

Given binary tree {1,#,2,3},

   1
         2
    /
   3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

思路:

写个非递归的前序遍历,用 stack.

代码:
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> ans;
        stack<TreeNode *> s;
        TreeNode *p = root;
        while(p != NULL || !s.empty())
        {
            while(p != NULL)
            {
                ans.push_back(p->val);
                s.push(p);
                p = p->left;
            }
            if(!s.empty())
            {
                p = s.top();
                s.pop();
                p = p->right;
            }
        }
        return ans;
    }
};
时间: 2025-01-05 03:22:18

【LeetCode】Agorithms 题集(一)的相关文章

LeetCode算法题-Min Stack(Java实现)

这是悦乐书的第177次更新,第179篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第36题(顺位题号是155).设计一个支持push,pop,top和在恒定时间内检索最小元素的堆栈. push(x) - 将元素x推入堆栈. pop() - 删除堆栈顶部的元素. top() - 获取顶部元素. getMin() - 检索堆栈中的最小元素. 例如: MinStack minStack = new MinStack(); minStack.push(-2); minSta

LeetCode算法题-Reverse Bits(Java实现)

这是悦乐书的第185次更新,第187篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第44题(顺位题号是190).给定32位无符号整数,求它的反转位.例如: 输入:43261596 输出:964176192 说明:43261596以二进制表示为00000010100101000001111010011100, 964176192以二进制表示为00111001011110000010100101000000. 本次解题使用的开发工具是eclipse,jdk使用的版本是1

LeetCode算法题-Number of 1 Bits(Java实现)

这是悦乐书的第186次更新,第188篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第45题(顺位题号是191).编写一个带无符号整数的函数,并返回它所具有的"1"位数.例如: 输入:11 输出:3 说明:整数11具有二进制表示00000000000000000000000000001011 输入:128 输出:1 说明:整数128具有二进制表示00000000000000000000000010000000 本次解题使用的开发工具是eclipse,jdk使

LeetCode算法题-Remove Linked List Elements(Java实现)

这是悦乐书的第189次更新,第191篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第48题(顺位题号是203).移除单链表中节点值为val的节点.例如: 输入:1-> 2-> 6-> 3-> 4-> 5-> 6,val = 6 输出:1-> 2-> 3-> 4-> 5 本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试. 02 第一种解法 特殊情况

LeetCode算法题-Power Of Two(Java实现)

这是悦乐书的第194次更新,第200篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第56题(顺位题号是231).给定一个整数,写一个函数来确定它是否是2的幂.例如: 输入:1 输出:true 说明:2^0 = 1 输入:16 输出:true 说明:2^4 = 16 输入:218 输出:false 本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试. 02 第一种解法 此解法是做乘法,新建一个变量,

LeetCode算法题-Lowest Common Ancestor of a Binary Search Tree

这是悦乐书的第197次更新,第203篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第59题(顺位题号是235).给定二叉搜索树(BST),找到BST中两个给定节点的最低共同祖先(LCA).根据维基百科上LCA的定义:"最低共同祖先在两个节点p和q之间定义为T中的最低节点,其中p和q都是后代(我们允许节点成为其自身的后代)." 给定二叉搜索树:root = [6,2,8,0,4,7,9,null,null,3,5] 6 / 2 8 / \ / 0 4 7 9

LeetCode算法题-First Bad Version(Java实现-三种解法)

这是悦乐书的第200次更新,第210篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第66题(顺位题号是278).您是产品经理,目前领导团队开发新产品.不幸的是,您产品的最新版本未通过质量检查.由于每个版本都是基于以前的版本开发的,因此坏版本之后的所有版本也是坏的. 假设您有n个版本[1,2,...,n]并且您想找出第一个坏的版本,这会导致以下所有版本都不好.您将获得一个API bool isBadVersion(版本),它将返回版本是否错误. 实现一个函数来查找第一

LeetCode算法题-Move Zeroes(Java实现-三种解法)

这是悦乐书的第201次更新,第211篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第67题(顺位题号是283).给定一个数组nums,写一个函数将所有0移动到它的末尾,同时保持非零元素的相对顺序.例如: 输入:[0,1,0,3,12] 输出:[1,3,12,0,0] 注意: 您必须在不制作数组副本的情况下就地执行此操作. 最小化操作总数. 本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试. 02

LeetCode算法题-Word Pattern(Java实现)

这是悦乐书的第202次更新,第212篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第68题(顺位题号是290).给定一个模式和一个字符串str,找到str是否完全匹配该模式.完全匹配是指在模式中的字母和str中的非空单词之间存在一一对应的关系.例如: 输入:pattern ="abba",str ="dog cat cat dog" 输出:true 输入:pattern ="abba",str ="dog