Twitter OA prepare: Equilibrium index of an array
Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in an arrya A: A[0] = -7, A[1] = 1, A[2] = 5, A[3] = 2, A[4] = -4, A[5] = 3, A[6]=0 3 is an equilibrium index, because:
A[0] + A[1] + A[2] = A[4] + A[5] + A[6] 6 is also an equilibrium index, because sum of zero elements is zero, i.e., A[0] + A[1] + A[2] + A[3] + A[4] + A[5]=0 7 is not an equilibrium index, because it is not a valid index of array A. Write a function int equilibrium(int[] arr, int n); that given a sequence arr[] of size n, returns an equilibrium index (if any) or -1 if no equilibrium indexes exist.
Method 1 (Simple but inefficient)
Use two loops. Outer loop iterates through all the element and inner loop finds out whether the current index picked by the outer loop is equilibrium index or not. Time complexity of this solution is O(n^2).
Method 2 (Tricky and Efficient)
The idea is to get total sum of array first. Then Iterate through the array and keep updating the left sum which is initialized as zero. In the loop, we can get right sum by subtracting the elements one by one. Thanks to Sambasiva for suggesting this solution and providing code for this.
O(n) time complexity
1) Initialize leftsum as 0
2) Get the total sum of the array as sum
3) Iterate through the array and for each index i, do following.
a) Update sum to get the right sum.
sum = sum - arr[i]
// sum is now right sum
b) If leftsum is equal to sum, then return current index.
c) leftsum = leftsum + arr[i] // update leftsum for next iteration.
4) return -1 // If we come out of loop without returning then
// there is no equilibrium index
#include <stdio.h> int equilibrium(int arr[], int n)
{
int sum = 0; // initialize sum of whole array
int leftsum = 0; // initialize leftsum
int i; /* Find sum of the whole array */
for (i = 0; i < n; ++i)
sum += arr[i]; for( i = 0; i < n; ++i)
{
sum -= arr[i]; // sum is now right sum for index i if(leftsum == sum)
return i; leftsum += arr[i];
} /* If no equilibrium index found, then return 0 */
return -1;
} int main()
{
int arr[] = {-7, 1, 5, 2, -4, 3, 0};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printf("First equilibrium index is %d\n", equilibrium(arr, arr_size)); getchar();
return 0;
}
Twitter OA prepare: Equilibrium index of an array的更多相关文章
- Twitter OA prepare: Visit element of the array
分析:就是建立一个boolean array来记录array里面每个元素的访问情况,遇到访问过的元素就停止visiting,返回未访问的结点个数 public int visiting(int[] A ...
- Twitter OA prepare: Flipping a bit
You are given a binary array with N elements: d[0], d[1], ... d[N - 1]. You can perform AT MOST one ...
- Twitter OA prepare: Two Operations
准备T家OA,网上看的面经 最直接的方法,从target降到1,如果是奇数就减一,偶数就除2 public static void main(String[] args) { int a = shor ...
- Twitter OA prepare: even sum pairs
思路:无非就是扫描一遍记录奇数和偶数各自的个数,比如为M和N,然后就是奇数里面选两个.偶数里面选两个,答案就是M(M-1)/2 + N(N-1)/2
- Twitter OA prepare: K-complementary pair
2sum的夹逼算法,需要sort一下.本身不难,但是tricky的地方在于允许同一个数组元素自己跟自己组成一个pair,比如上例中的[5, 5].而且数组本身就允许值相等的元素存在,在计算pair时, ...
- Twitter OA prepare: Anagram is A Palindrome
Algorithm: Count the number of occurrence of each character. Only one character with odd occurrence ...
- Twitter OA prepare: Rational Sum
In mathematics, a rational number is any number that can be expressed in the form of a fraction p/q ...
- twitter oa
字符串括号匹配有效性: 要求从直接return改成了返回yes or no.需要添加到list后break,然后每次循环之前,boolean要重新初始化. array index报错是什么鬼?算了,脑 ...
- 2Sigma OA prepare: Friends Circle
DFS & BFS: 关键在于构造graph package twoSigma; import java.util.ArrayList; import java.util.HashSet; i ...
随机推荐
- Android 使用tomcat搭建HTTP文件下载服务器
上一篇: Android 本地搭建Tomcat服务器供真机测试 1.假设需要下载的文件目录是D:\download1(注意这里写了个1,跟后面的名称区分) 2.设置 tomcat 的虚拟目录.在 {t ...
- 设置RabbitMQ远程ip登录
由于账号guest具有所有的操作权限,并且又是默认账号,出于安全因素的考虑,guest用户只能通过localhost登陆使用,并建议修改guest用户的密码以及新建其他账号管理使用rabbitmq. ...
- 一篇博客搞定redis基础
redis简介 redis 一款高性能key-value数据库,实际上多用作缓存队列或者消息分发(celery),但是最常常被用来做缓存. redis安装 源码安装 $ wget http://dow ...
- Unity3D Shader落雪效果
Shader "Custom/Snow" { Properties { _MainTex ("Base (RGB)", 2D) = "white&qu ...
- 分布式文件系统FastDFS架构剖析
ps.本文来自于网络 一.什么是FastDfs FastDFS是一个开源的轻量级分布式文件系统,它对文件进行管理,功能包括:文件存储.文件同步.文件访问(文件上传.文件下载)等,解决了大容量存储和负载 ...
- Android 调用系统相机拍照,生命周期重走OnCreate,导致无数据的解决办法
extends:http://blog.csdn.net/b275518834/article/details/42347903 BUG具体体现为 : (1) 摄像头拍照后图片数据不一定能返回 ; o ...
- 阿里云安装Oracle
#!/bin/bash #writed by kangjie -- ######################################### #如果没有交换分区swap,则创建 # #检查 ...
- Windows Server 2008 R2之二从介质安装 AD DS
可以使用 Ntdsutil.exe 为在域中创建的其他域控制器创建安装介质.通过从介质安装,可以最大程度地减少网络上目录数据的复制.有利于在远程站点中更高效地安装其他域控制器. 实验环境: 在Wind ...
- hdu2586(LCA最近公共祖先)
How far away ? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) T ...
- HttpClient 学习整理【转】
转自 http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html HttpClient 是我最近想研究的东西,以前想过的一些应用没能有很好的 ...