几道Leetcode题思路与代码

来源:互联网 发布:大数据时时彩极限方案 编辑:程序博客网 时间:2024/05/16 15:38

226. Invert Binary Tree

问题描述
Invert a binary tree.     4   /   \  2     7 / \   / \1   3 6   9to     4   /   \  7     2 / \   / \9   6 3   1
思路1
  • 把每个节点当成一个单元来看待,然后运用递归的思路
  • 对于每个单元,把节点的左右子节点交换即可
  • 左子节点指针指向右子节点,右子节点由递归函数返回;对于右子节点同理
  • 如果节点是空,返回空;如果节点不为空,则返回原节点
代码1
TreeNode* invertTree(TreeNode* root) {   if(NULL == root)       return NULL;   else   {       TreeNode* newleft=invertTree(root->right);       TreeNode* newright=invertTree(root->left);       root->left=newleft;       root->right=newright;       return root;   }}
思路2 非递归的方法
  • 【LeetCode】226. Invert Binary Tree

223 recrangle area

问题描述
Find the total area covered by two rectilinear rectangles in a 2D plane.Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.Assume that the total area is never beyond the maximum possible value of int.

这里写图片描述

思路
  • 覆盖面积=两个矩形面积之和-重叠区域面积
  • 重叠区域面积计算:两个矩形的左下角点的x坐标的最大值,确定重叠区左下角的x坐标;两个矩形右上角的x坐标的最小值,确定重叠区右上角的x坐标。同理对y坐标。
代码
int Solution::computeArea(int A,int B,int C,int D,int E,int F,int G,int H){    int area1=(C-A)*(D-B);    int area2=(G-E)*(H-F);    int over_area=overlap(A,B,C,D,E,F,G,H);    int area=area1+area2-over_area;    return area;    }int Solution::overlap(int A,int B,int C,int D,int E,int F,int G,int H){    int h1=Math.max(A,E);    int h2=Math.min(C,G);    int h=h2>h1?h2-h1:0;    int w1=Math.max(B,F);    int w2=Math.min(D,H);    int w=w2>w1?w2-w1:0;    return w*h;}

326. Power of Three && 342. Power of Four

问题描述
Given an integer, write a function to determine if it is a power of three.Follow up:Could you do it without using any loop / recursion?
教程

editorial solution

思路
  • 方法一:循环和迭代肯定是可以实现的
  • 方法二: 数学的方法n=3i=>i=log10(n)log10(3)?=
代码
bool isPowerOfThree(int n) {   int e=3;//e=4是以4为指数   double x=log10(n)/log10(3);   return x-int(x) == 0;// 判断double x 为整数}

231. Power of Two

问题描述
Given an integer, write a function to determine if it is a power of two.
思路
  • n<=0时,返回false
  • 连续除以2,如果余数为0,则继续,直到n=1未知,返回true;如果余数不为0,则退出,返回false
代码1:迭代
  bool isPowerOfTwo(int n)   {      int remainder;      bool flag=true;      if(n<=0)          return false;      while(n != 1)      {          remainder=n%2;          flag=true;          if(remainder !=0)          {              flag=false;              break;          }          n=n/2;      }      return flag; }
代码2:递归
bool Solution::isPowerOfTwo(int n){    if(n<=0)        return false;    if(n == 1)        return true;    else    {        int remainder=n%2;        if(remainder == 0)        {            n=n/2;            return isPowerOfTwo(n);        }        else            return false;    }}

169. Majority Element

问题描述
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.You may assume that the array is non-empty and the majority element always exist in the array.
思路
  • 统计每个数字出现的频率
  • 找出频率过半的数字
  • 使用unordered_map 数据结构
代码
int Solution::majorityElement(vector<int>& nums){    unordered_map<int,int> freqs;    for(int i=0;i<nums.size();i++)    {        freqs[nums[i]]++;    }    int majorE=0;    for(auto it:freqs)    {        if(it.second>nums.size()/2)        {            majorE= it.first;            break;        }    }    return majorE;}

171. Excel Sheet Column Number

问题描述
Related to question Excel Sheet Column TitleGiven a column title as appear in an Excel sheet, return its corresponding column number.For example:    A -> 1    B -> 2    C -> 3    ...    Z -> 26    AA -> 27    AB -> 28 
思路
  • 进制为26,起始值从开始
  • 先将string s反转,然后从低位开始计算到高位
代码
int Solution::titleToNumber(string s){    if(s.empty())        return 0;    reverse(s.begin(),s.end());    int n=0;    for(int i=0;i<s.size();i++)    {        int a=(s[i]-'A'+1)*pow(26,i);        n=n+a;    }    return n;}

389. Find the Difference

问题描述
Given two strings s and t which consist of only lowercase letters.String t is generated by random shuffling string s and then add one more letter at a random position.Find the letter that was added in t.Example:Input:s = "abcd"t = "abcde"Output:eExplanation:'e' is the letter that was added.
思路
  • 字符串t的位置时随机打乱的,因此可以用遍历
  • 字符串s中可能存在重复字符,因此遍历查找时要排除重复字符的影响
  • 字符串s为空时要单独考虑
  • 当字符串t的长度不断变小时,可能存在字符串程度为0的情况,也要考虑到
  • 设置一个标志位isDif
代码
char Solution::findTheDifference(string s,string t){    bool isDif=false;    if(s=="")        return t[0];    char a;    for(int i=0;i<t.size();i++)    {        isDif=true;        for(int j=0;j<s.size()&& s.size()>0;j++)        {            if(s[j]==t[i])            {                isDif=false;                s.erase(j,1);                break;            }        }        if(isDif==true)        {            a= t[i];            break;        }    }    return a;}

168. Excel Sheet Column Title

问题描述
Given a positive integer, return its corresponding column title as appear in an Excel sheet.For example:    1 -> A    2 -> B    3 -> C    ...    26 -> Z    27 -> AA    28 -> AB 
错误代码
// 错误的算法string Solution::convertToTitle(int n){    string titleStr;    int remainder=n%26;    while(n/26 != 0)    {        remainder=n%26;        if(remainder==0)        {            titleStr.push_back('Z');        }        else         {            titleStr.push_back('A'+remainder-1);        }        n=n-remainder*26;    }    if(remainder !=0 )    {        titleStr.push_back('A'+n-1);    }    reverse(titleStr.begin(),titleStr.end());    return titleStr;}
  • 在n=26,52等26的倍数时错误,会多增一位
  • 逻辑比较混乱,不清晰
正确思路
  • 这是26进制的题,类比10进制;
  • 不过起始值从1开始,因此需要减1
  • string 类 增的操作,可以用+,append和push_back 来完成
正确代码
string Solution::convertToTitle(int n){    string titleStr="";    while(n !=0)    {        int remainder=(n-1)%26;        titleStr.push_back('A'+remainder);        n=(n-1)/26;    }    //反转字符串    reverse(titleStr.begin(),titleStr.end());    return titleStr;}

237. Delete Node in a Linked List

问题描述
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
单链表的数据结构
// definition for singly-linked liststruct ListNode{    int val;    ListNode *next;    ListNode(int x):val(x),next(NULL){}};
思路
  • 输入是需要删除的链表节点
  • 可以直接把需要删除的节点替换成下一个节点,这样子就完成了节点删除
  • 当链表节点为空或者next属性为空,则直接返回,不删除
代码
void Solution::delectNode(ListNode* node){    if(node == NULL || node->next == NULL) return;    node->val=node->next->val;    node->next=node->next->next;}

100: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 a binary tree node. struct TreeNode  {     int val;     TreeNode *left;     TreeNode *right;     TreeNode(int x) : val(x), left(NULL), right(NULL) {} };
错误代码
//wrong code bool Solution::isSameTree_wrong(TreeNode* p,TreeNode* q){    if(p->val != q->val)        return false;    else if((p->left == NULL && q->left != NULL) || (p->left != NULL && q->left == NULL)||        (p->right == NULL && q->right != NULL) || (p->right != NULL && q->right == NULL))        return false;    else    {        bool left=isSameTree_wrong(p->left,q->left);        bool right=isSameTree_wrong(p->right,q->right);        if(left && right)            return true;        else             return false;    }}
  • 逻辑上不清晰,把节点和左右子树都考虑进去了,但又考虑不对
思路
  • LeetCode(100)Same Tree
  • 明显用递归,树类型的题目,大多数可以用递归解决
  • 以一个节点为单位来考虑,避免情况复杂
正确代码
bool isSameTree(TreeNode* p,TreeNode* q){    if(p ==NULL && q != NULL)        return false;    else if(p !=NULL && q ==NULL)        return false;    else if(p == NULL && q == NULL)        return true;    else if((p != NULL && q != NULL)&& (p->val !=q->val))        return false;    else     {        return (isSameTree(p->left,q->left) && isSameTree(p->right,q->right));    }}
测试代码
struct TreeNode p1(1),p2(2),p3(3);    p1.left=&p2;    p1.right=&p3;    struct TreeNode q1(1),q2(2),q3(3);    q1.left=&q2;    q1.right=&q3;    Solution Sol;    bool x=false;    x=Sol.isSameTree(&p1,&q1);

263:Ugly Number

question description
Write a program to check whether a given number is an ugly number.Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.Note that 1 is typically treated as an ugly number.
思路
  • 非正整数不是ugly number
  • 1不是ugly number
  • 被2,3,5连续除尽的数,也就是没有余数,最后商为1的数是ugly number
  • 当商不是1时,则不是ugly number
code
bool isUgly(int num){    if(num <= 0)        return false;    else if(num==1)        return true;    while(num%2 == 0) num=num/2;    while(num%3 == 0) num=num/3;    while(num%5 == 0) num=num/5;    if(num == 1)        return true;    else        return false;}

202: Happy Number

问题描述:
Write an algorithm to determine if a number is "happy".A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.Example: 19 is a happy number12 + 92 = 8282 + 22 = 6862 + 82 = 10012 + 02 + 02 = 1
思路
  • 这是一个递归问题
  • 数字可以用vector存储
  • 当不是幸福数时,设置一个循环次数上限
代码
bool isHappy(int n){    int n_src=n;//保存原来的n    int loopnum=0;    while(n != 1)    {        loopnum++;        vector<int> digitsVec;        while(n/10 !=0)        {            digitsVec.push_back(n%10);            n=n/10;        }        digitsVec.push_back(n);        n=0;        for(int i=0;i<digitsVec.size();i++)        {            n=n + digitsVec[i]*digitsVec[i];        }        if(n == n_src || loopnum >100)            return false;    }    return true;}
0 0
原创粉丝点击