83.删除排序列表中的重复元素
第一次做Java的链表题,果断不会。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur=head;
if(head==null)
return null;
while(cur.next!=null){
if(cur.val==cur.next.val){
cur.next=cur.next.next;
}
else
cur=cur.next;
}
return head;
}
}
643.子数组最大平均数I
这题我用一般方法又果断超时。以下是我的报错代码。
class Solution {
public double findMaxAverage(int[] nums, int k) {
double ans=Integer.MIN_VALUE;
if(nums.length==1)
return nums[0]+0.0;
for(int i=0;i<=nums.length-k;i++){
long num=0L;
double average=0;
for(int j=0;j
num+=(long)nums[i+j];
}
average=(num+0.0)/k;
ans=Math.max(ans,average);
}
return ans;
}
}
以下是标答。
class Solution {
public double findMaxAverage(int[] nums, int k) {
int sum = 0;
int n = nums.length;
for (int i = 0; i < k; i++) {
sum += nums[i];
}
int maxSum = sum;
for (int i = k; i < n; i++) {
sum = sum - nums[i - k] + nums[i];
maxSum = Math.max(maxSum, sum);
}
return 1.0 * maxSum / k;
}
}