寻找数组的中心下标
题目
给你一个整数数组 nums ,请计算数组的 中心下标 。
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。
如果数组有多个中心下标,应该返回 最靠近左边 的那一个。如果数组不存在中心下标,返回 -1 。
示例 1:
输入:nums = [1, 7, 3, 6, 5, 6]
输出:3
解释:
中心下标是 3 。
左侧数之和 sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 ,
右侧数之和 sum = nums[4] + nums[5] = 5 + 6 = 11 ,二者相等。
示例 2:
输入:nums = [1, 2, 3]
输出:-1
解释:
数组中不存在满足此条件的中心下标。
思路
如何巧妙的处理i项的和 以及 n-i项的和 是一个技术活
代码
class Solution {
public int pivotIndex(int[] nums) {
// And record all Numbers
int sum = 0;
int leftsum= 0;
int rightsum = 0;
for (int num:nums){
sum += num;
}
for (int i = 0 ; i < nums.length ;i++){
leftsum += nums[i];
rightsum = sum - leftsum + nums[i];
if (leftsum == rightsum){return i;}
}
return -1;
}
}
实现Strstr()
题目
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
示例 1:
输入:haystack = "hello", needle = "ll"
输出:2
示例 2:
输入:haystack = "aaaaa", needle = "bba"
输出:-1
代码
class Solution {
public int strStr(String haystack, String needle) {
if (Objects.equals(needle, "") || Objects.equals(haystack,needle)){return 0;}
if (Objects.equals(haystack, "")){return -1;}
char [] haystr = haystack.toCharArray();
char [] neestr = needle.toCharArray();
int index;
for (int i = 0 ; i <= haystr.length-neestr.length ; i++){
index = 0;
for (int j = 0 ; j < neestr.length;j++){
if (haystr[i+j] == neestr[j]){index++;}
if (index == neestr.length){return i;}
}
}
return -1;
}
}
4 条评论
你也在刷題嗎,真不錯
偶尔吧
带我带我带我大哥
我比较菜拉拉拉∠( ᐛ 」∠)_