- 实现一个函数,能够计算整型十进制对应的二进制里的1的数目
leetcode191
思路:主要是利用位运算,整型数据与1相与,对应二进制末尾为0,则结果为0,末尾为1,则结果为1;无符号整型,>>运算符高位用0填充。int hammingWeight(uint32_t n) {//typedef unsigned long uint32_t; int count=0; while(n>0){ if(n & 1) ++count; n=n>>1; } return count; }
其实C++里面有相同功能的函数,__builtin_popcount(),用于计算无符号32位整数对应二进制里的1的个数,就在#incldue <iostream>头文件里。
#include <iostream> using namespace std; int main(){ int a=11; cout<<__builtin_popcount(a)<<endl; return 0; }
- 判断两个链表是否相交,并输出交点
leetcode160执行用时 :104 ms, 在所有 C++ 提交中击败了31.64%的用户
内存消耗 :16.6 MB, 在所有 C++ 提交中击败了63.67%的用户
思路:首先判断是否有焦点,其次再找到焦点,这是贝壳面试时遇到的一个题目,很简单,但是刚才写的时候心里觉得简单就随便写,导致逻辑链丢失,代码也写了半个小时才写出来。ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(headA==nullptr && headB==nullptr) return nullptr; ListNode *p1=headA; ListNode *p2=headB; int l1=1,l2=1; while(p1 && p1->next){ p1=p1->next; ++l1; } while(p2 && p2->next){ p2=p2->next; ++l2; } if(p1==p2 && p1){ p1=headA; p2=headB; if(l1>l2){ for(int i=0;i<l1-l2;++i){ p1=p1->next; } }else{ for(int i=0;i<l2-l1;++i){ p2=p2->next; } } while(p1!=p2){ p1=p1->next; p2=p2->next; } return p1; }else return nullptr; }
- 给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
leetcode73
思路: - 剑指offer27题,二叉搜索树转换成双向链表
思路,借助中序遍历void inorder(BinaryTreeNode* *pList,BinaryTreeNode* root){ if(root==nullptr) return; if(root->left){ inorder(pList,root->left); } root->left=*pList; if(*pList!=nullptr){ *pList->right=root; } *pList=root; if(root->right){ inorder(pList,root->right); } } BinaryTreeNode* Convert(BinaryTreeNode* root){ BinaryTreeNode* pList=nullptr; inorder(&pList,root); BinaryTreeNode* pListHead=pList; while(pListHead && pListHead->left){//需要返回头结点 pListHead=pListHead->left; } return pListHead; }
瓜子二手车面试准备(leetcode,剑指offer)
最新推荐文章于 2021-02-07 23:59:09 发布