leetcode刷题(一)

一、985查询后的偶数和

思路1:首先从查询数组中取出第一个元素,把它加在数组A中,接着遍历整个数组A求得偶数和。代码如下:

class Solution {
    public int[] sumEvenAfterQueries(int[] A, int[][] queries) {
        int[] res = new int[queries.length];
        for(int i = 0 ; i < queries.length ; i++){
            A[queries[i][1]] += queries[i][0];
            res[i] = add(A);
        }
        return res;
    }

    public int add(int[] A){
        int sum = 0;
        for(int i = 0 ; i < A.length ; i++){
            if(A[i] % 2 == 0)
                sum += A[i];
        }
        return sum;
    }
}

题虽然解出来了,但是运行之后发现速度很慢。

思路2:a.先求一遍数组A中偶数和sum

            b.遍历查询数组,对所操作的元素进行判断,分为2步:

                ①之前是偶数   ,减去这个偶数。

                ②加上数字后是偶数,就加上这个偶数。

class Solution {
    public int[] sumEvenAfterQueries(int[] A, int[][] queries) {
        int sum = 0;
        for(int a : A)
            if(a % 2 == 0)
                sum += a;
        int[] res = new int[queries.length];
        for(int i = 0 ; i < queries.length ; i++){
            int val = queries[i][0];
            int index = queries[i][1];
            if(A[index] % 2 == 0) sum -= A[index];
            A[index] += val;
            if(A[index] % 2 == 0) sum += A[index];
            res[i] = sum;
        }
        return res;
    }
}

二、206反转链表

思路1:迭代法。

在遍历列表时,将当前节点的 next 指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。在更改引用之前,还需要另一个指针来存储下一个节点。

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while(cur != null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

思路2:递归法。假设此时只有两个节点A,B,且A→B,我们可以通过A.next.next = A,A.next = null进行反转。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next ==null ) return head;
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }   
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值