tus124
BAN USERint[] findMinTrianglePerimeter(int[] a) {
a = sort(a);
for(int i=0; i<a.Length-2; i++) {
for(int j=i+1; j<a.Length-1; j++) {
if(a[i] + a[j] > a[j+1]) {
int[] result = { a[i], a[j], a[j+1] };
return result;
}
}
}
return null;
}
int[] sort(int[] a) {
return quickSort(a, 0, a.Length);
}
int[] quickSort(int[] a, int low, int high) {
int pivot = partition(a, low, high);
quickSort(a, low, pivot-1);
quickSort(a, pivot+1; high);
return a;
}
int partition(int[] a, int low, int high) {
int i=low, j=high, pivot = a[(low+high)/2];
while(i<=j) {
while(a[i] < pivot) i++;
while(a[j] > pivot) j--;
if(i <= j) swap(ref a[i++], ref a[j--]);
}
return i;
}
void swap(ref int a, ref int b) {
int temp = a;
a = b;
b = temp;
}
// n = 8
int calculateChessBoardSquares(int n) {
int result = 0;
for(int i=1; i<=n; i++) {
result += i * i;
}
return result;
}
// formula for calculating sum: n^3/3 + n^2/2 + n/6
int calculateChessBoardSquaresWithoutLoop(int n) {
return Math.Pow(n,3)/3 + Math.Pow(n,2)/2 + n/6
}
string reverse(string s) {
int length = s.Length();
char[] a = s.toCharArray();
for(int i=0, j = length - 1; i<=j; i++, j--) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a.toString();
}
List<string> reverseWords(string s) {
List<string> result = new List<string>();
string[] words = s.split(" ");
foreach(word in words) {
result.add(reverse(word));
}
return result;
}
Node findNToLastNode(Node head, int N) {
Node current = head;
Node behind = head;
for(int i=0; i<N; i++) {
if(current.next != null)
current = current.next;
}
while(current.next != null) {
current = current.next;
behind = behind.next;
}
return behind;
}
// a -> b -> c -> d -> e
void print2ndToLastNodeTest(Node head) {
Node n = findNToLastNode(head, 2);
Assert.isTrue(n != null);
Assert.isTrue(n.value = "c");
}
we simply have to merge the first two linked list and loop thru all the k linked list to merge.
public class LinkedList {
public int value { get; set; }
LinkedList next { get; set; }
public LinkedList(int v) {
value = v;
next = null;
}
}
public class LinkedListAlgorithms {
public LinkedList Merge(LinkedList[] a, int k) {
LinkedList result = merge(a[0], a[1]);
for(int i=2; i<k; i++) {
result = merge(result, a[i]);
}
return result;
}
private LinkedList merge(LinkedList a, LinkedList b) {
LinkedList p1 = a;
LinkedList p2 = b;
LinkedList head = new LinkedList(0);
LinkedList prev = head;
while( p1 != null && p2 != null ) {
if(p1.value < p2.value) {
prev.next = p1;
p1 = p1.next;
}
else {
prev.next = p2;
p2 = p2.next;
}
prev = prev.next;
}
if(p1 != null) prev.next = p1;
if(p2 != null) prev.next = p2;
return head.next;
}
}
int[] getSums(int[] a, int n)
{
Array.Sort<int>(a);
Array.Reverse(a);
int sum = 0;
int[] result = new int[a.Length];
int k = 0;
for (int i = 0; i < a.Length; i++)
{
if (a[i] + sum <= n)
{
sum += a[i];
result[k++] = a[i];
}
}
if (sum == n)
{
Array.Resize(ref result, k);
return result;
}
return new int[0];
}
- tus124 August 02, 2015