【LeetCode】Agorithms 题集(一)

【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;
    }
};

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/115491.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Java实现AES加密与解密(秘钥)

    Java实现AES加密与解密(秘钥)

    2021年4月9日
    151
  • elasticsearch面试常问问题_java面试题汇总

    elasticsearch面试常问问题_java面试题汇总Elasticsearch是基于Lucene的Restful的分布式实时全文搜索引擎,每个字段都被索引并可被搜索,可以快速存储、搜索、分析海量的数据。全文检索是指对每一个词建立一个索引,指明该词在文章中出现的次数和位置。当查询时,根据事先建立的索引进行查找,并将查找的结果反馈给用户的检索方式。这个过程类似于通过字典中的检索字表查字的过程。**(1)index索引:**索引类似于mysql中的数据库,Elasticesearch中的索引是存在数据的地方,包含了一堆有相似结构的文档数据。**(2

    2022年9月3日
    2
  • java图书馆新地址_最受Java开发者喜爱的5款开源IDE盘点

    java图书馆新地址_最受Java开发者喜爱的5款开源IDE盘点开源最前线(ID:OpenSourceTop)猿妹编译项目地址:https://opensource.com/article/20/7/ide-java在TIOBE编程语言排行中,Java始终排在前三名,现今有700万到1000万的Java开发人员。许多应用程序的所有代码都是用Java编写的,这意味着集成开发环境(IDE)很重要,因为它是开发人员编写、测试和运行Java程序必备的工具…

    2022年7月8日
    42
  • webstorm 插件_vscode插件开发文档

    webstorm 插件_vscode插件开发文档webstorm集成了很多强大的前端插件。使用的时候只需要在webstorm中搜索plugin就可以出来一堆,选择需要的安装j

    2022年9月10日
    0
  • String转换Long两种方式

    Long.ValueOf(“String”)与Long.parseLong(“String”)的区别Long.ValueOf(“String”)返回Long包装类型Long.parseLong(“String”)返回long基本数据类型

    2022年4月5日
    66
  • 用js在控制台打印html页面,vue 使用print-js 打印html页面

    用js在控制台打印html页面,vue 使用print-js 打印html页面Print.js官网官网优点:可以打印多种格式的内容(pdf、json、html等)打印json时可以添加表头。打印html页时可以继承原有页面的样式,局部打印,过滤掉要打印的元素,及其方便。一、vue安装命令:npminstallprint-js–save二、引入这个引入不需要在main.js中,直接在使用的.vue中引入即可这里颜色虽然是灰色,但是也要添加,否则会报错。三、编码我这里…

    2022年10月21日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号