GeeksforGeeks
文章平均质量分 51
spongewxy
这个作者很懒,什么都没留下…
展开
-
Find the element that appears once
来源:http://www.geeksforgeeks.org/find-the-element-that-appears-once/问题:在一个数组中,其中有一个元素只出现一次,其余元素都出现三次,如何在O(n)的时间复杂度和O(1)的复杂度内找到那个元素。首先我的想法是,一个数如果出现了三次,则这个数的二进制对应的位上1的个数肯定为3.这样我们可以枚举每一位,计算所有数转载 2015-06-17 22:17:28 · 384 阅读 · 0 评论 -
Detect if two integers have opposite signs
来源: http://www.geeksforgeeks.org/detect-if-two-integers-have-opposite-signs/不采用算术运算符,我们可以采用以下几种方法。(1) 首先异或操作可以判断两个数是否是同号的,因为异或运算是将符号位包括在内的,非负数符号位为0,负数符号位为1,所以0^1=1,异或的结果符号位1,即为负数。#includ转载 2015-06-17 23:14:59 · 456 阅读 · 0 评论 -
位运算总结
总结一些简单的位运算的操作并利用位运算来解决一些问题,注意: &, |, ^在进行位运算时是将操作数的符号位也考虑在内的。求解整数的绝对值int abs(int a) { return (a ^ (a>>31)) - (a>>31);}求两个数的最大值int max(int a, int b) { return (b&((a-b)>>31)) | (a&(~(a-b)>>3原创 2016-07-25 23:09:45 · 653 阅读 · 0 评论 -
Find a Mother Vertex in a Graph
Find a Mother Vertex in a Graph解题思路:存在两种方法可以解决这个问题 1. 并查集 我们利用并查集维护一个一个顶点为根节点且其子树的所有节点均可由该根节点到达,维护这样的一个个集合。合并时按照有向边的指向合并即可。 2.直接dfs 假设如果存在一棵有某个顶点生成的dfs树,则我们只需要对原先的有向图不断地进行dfs即可,保存该趟dfs最后遍历的顶点。最终判断该原创 2016-07-29 20:16:47 · 690 阅读 · 0 评论 -
Shortest Path in a weighted Graph where weight of an edge is 1 or 2
Shortest Path in a weighted Graph where weight of an edge is 1 or 2解题思路: bfs适用于求解权值相同的图的最短路径。因此对原图进行改造,拆点u–>u,u’。其中u负责入边,u’负责出边。建图过程:w(u,u’)=1,如果w(u,v)=1,建边(u’,v)=0;如果w(u,v)=2,则建边(u’,v)=1。通过上面建图过程,我们只需原创 2016-07-29 22:49:58 · 500 阅读 · 0 评论 -
Print all Jumping Numbers smaller than or equal to a given value
Print all Jumping Numbers smaller than or equal to a given value解题思路: 1. bfs 从0开始搜索,沿着跳跃数的规则进行扩展,找出所有小于等于给定值的跳跃数的个数。之所以能够用bfs求解是因为即使给定一个很大的数,满足条件的跳跃数的数目也是很小的,因此整个bfs的搜索空间是很小的,足够高效。 2.数位DP dp[i][j]:原创 2016-07-30 09:58:10 · 519 阅读 · 0 评论 -
Assign directions to edges so that the directed graph remains acyclic
Assign directions to edges so that the directed graph remains acyclic解题思路:首先我们考虑怎么加边,假设原图只有有向边构成。对于每一条无向边(u,v)如果在原图中u->v是可达的,则我们添加的这条边的指向肯定是u->v;反过来如果v->u是可达的,则添加的边的指向肯定是v->u;如果u->v,v->u均不可达,则添加的新边的指向可原创 2016-07-30 11:28:05 · 609 阅读 · 0 评论 -
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Given n cities and distances between every pair of cities, select k cities to place warehouses (or ATMs or Cloud Server) such that the maximum distance of a city to a warehouse (or ATM or Cloud Server)转载 2016-07-30 11:49:06 · 1380 阅读 · 0 评论