var sum = 0;
function processData(input) {
var lines = input.split("\n");
var n = parseInt(lines[0]);
var arr = lines[1].split(" ");
for (var i = 0; i < input.length; i++) {
sum += parseInt(arr[i]);
}
console.log(sum);
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
Thursday, October 29, 2015
Simple Array Sum Javascript
HackerRank.com Simple Array Sum Javascript
Tuesday, October 27, 2015
Two Sum via C#
Problem: Given an array of integers, find two numbers such that they add up to a specific target number.
Answer via C# using HashTable:
Answer via C# using HashTable:
public class Solution {
public int[] TwoSum(int[] nums, int target) {
List<int> arr = new List<int>();
Hashtable hashTable = new Hashtable();
for (int i = 0; i < nums.Length;i++)
{
hashTable[nums[i]] = i;
}
for (int i = 0; i < nums.Length; i++)
{
// get key2, index2
var key2 = target - nums[i];
if (hashTable.Contains(key2) && ((Int32)hashTable[key2] != i) && ((Int32)hashTable[key2] > i))
{
int i2 = (Int32)hashTable[key2];
arr.Add(i + 1);
arr.Add(i2 + 1);
}
}
return arr.ToArray();
}
}
Rotate Array via Javascript
Leetcode rotate array via Javascript using reversal:
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
if(nums.length === 0) {
throw "provide valid array";
}
k = k % nums.length;
//length of first part
var a = nums.length - k;
reverse(nums, 0, a-1);
reverse(nums, a, nums.length-1);
reverse(nums, 0, nums.length-1);
};
function reverse(arr, left, right){
while(left < right){
var temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
Subscribe to:
Posts (Atom)