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 
#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; i1;
        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 

#define ARRLEN 9

int FindSingleNum(int arr[], int len)
{
    int ret = 0;
    int i;
    for(i=0; ireturn 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))
    }
};

你可能感兴趣的:(笔试题,LeetCode)