-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLastStoneWeight.cs
More file actions
74 lines (59 loc) · 1.91 KB
/
LastStoneWeight.cs
File metadata and controls
74 lines (59 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Collections.Generic;
using System.Text;
namespace CodeForecs
{
//https://leetcode.com/problems/last-stone-weight/
class LastStoneWeightSolution
{
public class StonesObject : IComparable<StonesObject>
{
public int Value { get; set; }
public StonesObject(int value)
{
Value = value;
}
public int CompareTo(StonesObject obj)
{
return obj.Value.CompareTo(this.Value);
}
}
public int LastStoneWeight(int[] stones)
{
List<StonesObject> sortedStones = new List<StonesObject>();
foreach(int i in stones)
{
sortedStones.Add(new StonesObject(i));
}
sortedStones.Sort();
/*
foreach (var obj in sortedStones)
{
Console.WriteLine(obj.Value);
}
*/
while(sortedStones.Count > 1)
{
int result = SmashStones(sortedStones[0].Value, sortedStones[1].Value);
sortedStones.RemoveAt(0);
sortedStones.RemoveAt(0);
if (result != 0)
{
StonesObject newStoneObject = new StonesObject(result);
int index = sortedStones.BinarySearch(newStoneObject);
if(index < 0)
{
index = ~index;
}
sortedStones.Insert(index, newStoneObject);
}
}
return sortedStones.Count == 0 ? 0 : sortedStones[0].Value;
}
public int SmashStones(int firstStone, int secondStone)
{
return firstStone != secondStone ?
firstStone - secondStone : 0;
}
}
}