[LeetCode] Arithmetic Slices II
来源:互联网 发布:淘宝宝贝图片下载器 编辑:程序博客网 时间:2024/06/07 15:13
A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, these are arithmetic sequences:
1, 3, 5, 7, 97, 7, 7, 73, -1, -5, -9
The following sequence is not arithmetic.
1, 1, 2, 5, 7
A zero-indexed array A consisting of N numbers is given. A subsequence slice of that array is any sequence of integers (P0, P1, ..., Pk) such that 0 ≤ P0 < P1 < ... < Pk < N.
A subsequence slice (P0, P1, ..., Pk) of array A is called arithmetic if the sequence A[P0], A[P1], ..., A[Pk-1], A[Pk] is arithmetic. In particular, this means that k ≥ 2.
The function should return the number of arithmetic subsequence slices in the array A.
The input contains N integers. Every integer is in the range of -231 and 231-1 and 0 ≤ N ≤ 1000. The output is guaranteed to be less than 231-1.
Example:
Input: [2, 4, 6, 8, 10]Output: 7Explanation:All arithmetic subsequence slices are:[2,4,6][4,6,8][6,8,10][2,4,6,8][4,6,8,10][2,4,6,8,10][2,6,10]
public class Solution {//其中 map数组中每个HashMap中key表示对应的差值,而value表示对应差值的长度大于等于2的数组的个数//map[i].put(key,getOrDefault(map[i], key)+count+1); getOrDefault(map[i], key)+count表示不断累加之前的长度大于等于2的数组的个数//+1 表示a[i]与a[j]组成的长度为2的数组 public int numberOfArithmeticSlices(int[] a) { if(a.length<3) return 0; int re=0; HashMap<Integer, Integer>[] map=new HashMap[a.length]; for(int i=0;i<a.length;i++){ map[i]=new HashMap<Integer,Integer>(); for(int j=0;j<i;j++){long temp=(long)a[i]-a[j];if(temp>Integer.MAX_VALUE||temp<Integer.MIN_VALUE) continue;int key=(int)temp;int count=getOrDefault(map[j],key);map[i].put(key,getOrDefault(map[i], key)+count+1);re+=count; } } return re; } public int getOrDefault(HashMap<Integer,Integer> map,int key){ if(map.containsKey(key)) return map.get(key); else return 0; } }
- [LeetCode] Arithmetic Slices II
- [LeetCode]446. Arithmetic Slices II
- LeetCode 446. Arithmetic Slices II
- [Leetcode] 446. Arithmetic Slices II
- leetcode 446. Arithmetic Slices II
- LeetCode 446. Arithmetic Slices II - Subsequence
- LeetCode 446. Arithmetic Slices II - Subsequence
- Leetcode-446. Arithmetic Slices II - Subsequence
- Arithmetic Slices II - Subsequence
- 446. Arithmetic Slices II
- 446. Arithmetic Slices II
- Arithmetic Slices II
- 446. Arithmetic Slices II
- Arithmetic Slices II
- 446. Arithmetic Slices II
- 446. Arithmetic Slices II
- [LeetCode]413.Arithmetic Slices
- LeetCode: Arithmetic Slices
- java中SocktTCP相关案例
- 磁盘调度 C语言实现
- 【LeetCode】48. Rotate Image
- POJ 1923 Fourier's Lines 笔记
- 批量处理(批量查找)的简单应用--xargs、exec、grep
- [LeetCode] Arithmetic Slices II
- 我的博客搬家啦
- MFC BEGIN_MESSAGE_MAP()
- 第五章 画蛇添足
- 我的博客即将入驻“云栖社区”,诚邀技术同仁一同入驻。
- 关于xcode8的建立依赖其他第三方库(cocoapods管理)的静态库framework
- [YTU]_2641 9 填空题:静态成员---计算学生个数)
- Java后台之路(05)-XML
- android developer tiny share-20170607