M3W3-LeetCode入门级三题

1.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?

【思路一】
假设原始数组为A,再创建一个数组B,将数组A中带判断的元素一次存入数组B,存入前与数组B中的元素一次作对比(数组B最开始没有元素),若找到相同的,就将数组B中的这个元素赋值为0,否则将数组A的这个带判断元素存入数组B。
最终数组B中只存在一个元素不是0,若B中的所有元素都为0,满足题目要去的数组元素就是0,否则输出不是0的元素。

#include <stdio.h>
#defien ARRLEN 9

int singleNumber(int A[], int n) {
    int newLen = n/2;
    int saveTwiceNum[128] = {0};
    int i;
    int j = 0;
    int k;
    int flag;

    for(i=0; i<n; i++){
        flag = 1;
        for(k=0; k<=j; k++){
            if(saveTwiceNum[k] == A[i]){
                saveTwiceNum[k] = 0;
                flag = 0;
                break;
            }
        }
        if(flag)
            saveTwiceNum[j++] = A[i];
    }

    for(j=0; j<=newLen; j++){
        if(saveTwiceNum[j]){
            return saveTwiceNum[j];
        }
    }
    return 0;
}

void main()
{
    int A[ARRLEN] = {1, 2, 3, 2, 1, 5, 6, 5, 6};
    printf("%d\n", singleNumber(A, ARRLEN));
}
/****************************************************
测试结果为3
*****************************************************/

【思路二】
这个是参考网络上的做法,不需要很复杂的写法,就是使用异或(一个数异或其本身为0)

#include <stdio.h>

#define ARRLEN 9

int FindSingleNum(int arr[], int len)
{
    int ret = 0;
    int i;
    for(i=0; i<len; i++){
    ret ^= arr[i]; 
    }
    return ret;
}


void main()
{
    int arr[ARRLEN] = {1, 2, 3, 2, 1, 5, 6, 5, 6};
    printf("%d\n", FindSingleNum(arr, ARRLEN));
}

2.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.

【思路】
要得到树的深度,肯定要遍历这个树,所以首先想到的就是树的遍历,递归什么的。

public int maxDepth(TreeNode root){    
    if(root == NULL)        
        return 0;

    int lDepth = maxDepth(root->left);
    int rDepth = maxDepth(root->right);
    //加1相当于自增,通过递归累加深度
    return 1 + (lDepth > rDepth ? lDepth : rDepth);
    }

3.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) {
        if(NULL == p && NULL == q)
            return true;
    if(NULL == p || NULL == q)
        return false;
    if(p->val != q->val)
        return false;

    return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right))
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值