problem:
We have a collection of stones, each stone has a positive integer weight.
Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:
If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.
At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)
//1046:Last Stone Weight
//i:初始想法,最简单的暴力循环:
对于给定的数组:
1:如果数组长度为1,直接放回当前结果
2:数组长度大于一,排序,从尾到头遍历,i,j(i>j)两个位置数值每次比较:
- 相等就把两个位置的数字1001,i,j别剪掉2
- 不相等就把把i的位置置为相减得到的数值,j的位置置为1001,排序,i,j分别剪掉1
3,判断i<0 or j<0,成立转4,不成立转2
4,如果第零个位置为1001,返回0,否则返回当前值
java
class Solution {
public int lastStoneWeight(int[] stones) {
int length=stones.length;
if(length==1){
return stones[0];
}
int i=length-1,j=i-1;
Arrays.sort(stones);
while(i>=0 && j>=0){
if(stones[i]==stones[j]){
stones[i]=1001;
stones[j]=1001;
i-=2;
j-=2;
}
else{
stones[j]=stones[i]-stones[j];
stones[i]=1001;
Arrays.sort(stones);
--i;
--j;
}
}
if(stones[0]==1001){
return 0;
}
return stones[0];
}
}
python
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
length=len(stones)
if length<1:
return 0;
if length==1:
return stones[0]
i=length-1
j=i-1
stones.sort()
while i>=0 and j>=0:
if stones[i]==stones[j]:
stones[j]=stones[i]=1001
i-=2
j-=2
else:
stones[j]=stones[i]-stones[j]
stones[i]=1001
i-=1
j-=1
stones.sort()
if stones[0]==1001:
return 0
return stones[0]
//ii:
//自己写排序:
java
class Solution {
// 选择排序之shell排序
public void shellsort(int [] nums){
int length=nums.length;
if(length<2){
return;
}
for(int d=length/2;d>0;d/=2){
for(int i=d;i<length;++i){
for(int j=i-d;j>=0;j-=d){
if(nums[j]<nums[j+d]){
int temp=nums[j];
nums[j]=nums[j+d];
nums[j+d]=temp;
}
}
}
}
}
public int lastStoneWeight(int[] stones) {
int length=stones.length;
if(length==1){
return stones[0];
}
else if(length==2){
return Math.abs(stones[1]-stones[0]);
}
shellsort(stones);
System.out.println(Arrays.toString(stones));
for(int i=0;i<length-1;++i){
if(stones[0]==stones[1]){
stones[0]=0;
stones[1]=0;
}
else{
stones[0]=stones[0]-stones[1];
stones[1]=0;
}
shellsort(stones);
}
return stones[0];
}
}