525涣楷、給定一個(gè)二進(jìn)制數(shù)組 nums , 找到含有相同數(shù)量的 0 和 1 的最長(zhǎng)連續(xù)子數(shù)組,并返回該子數(shù)組的長(zhǎng)度。
-(int)findMaxLength:(NSArray *)arr{
int res = 0,sum = 0;
NSMutableArray *numArr = [NSMutableArray array];
for (int i = 0; i < arr.count; i++) {
if([arr[i] isEqual:[NSNumber numberWithInt:0]]){
[numArr addObject:@-1];
}else{
[numArr addObject:@1];
}
}
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
// [dic setObject:@"-1" forKey:@"0"];
for (int i = 0; i < numArr.count; i++) {
sum = sum + [numArr[i] intValue];
if (![dic.allKeys containsObject:[NSString stringWithFormat:@"%d",sum]]) {
[dic setObject:[NSString stringWithFormat:@"%d",i] forKey:[NSString stringWithFormat:@"%d",sum]];
}else{
int t = i - [[dic objectForKey:[NSString stringWithFormat:@"%d",sum]] intValue];
NSLog(@"兩個(gè)重復(fù)數(shù)字質(zhì)檢距離長(zhǎng)度->%d",t);
NSLog(@"res->%d",res);
if (res > (i - [[dic objectForKey:[NSString stringWithFormat:@"%d",sum]] intValue])) {
}else{
res = i - [[dic objectForKey:[NSString stringWithFormat:@"%d",sum]] intValue];
}
}
}
return res;
}
-(int)findMaxlngth:(NSArray *)arr{
int count = 0;
int max = 0;
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
for (int i = 0; i<arr.count; i++) {
if ([arr[i] isEqual:[NSNumber numberWithInt:0]]) {
count++;
}else{
count--;
}
if(![dic.allKeys containsObject:[NSString stringWithFormat:@"%d",count]]){
[dic setObject:[NSString stringWithFormat:@"%d",i] forKey:[NSString stringWithFormat:@"%d",count]];
}else{
int temp = [[dic objectForKey:[NSString stringWithFormat:@"%d",count]] intValue];
if (i - temp > max) {
max = i - temp;
}
if (count == 0 && max<i+1) {
max = i+1;
}
}
}
return max;
}
160堤撵、相交鏈表:給你兩個(gè)單鏈表的頭節(jié)點(diǎn) headA 和 headB ,請(qǐng)你找出并返回兩個(gè)單鏈表相交的起始節(jié)點(diǎn)羽莺。如果兩個(gè)鏈表沒有交點(diǎn)实昨,返回 null 。
1禽翼、哈希表屠橄,遍歷A鏈表,將A鏈表節(jié)點(diǎn)存儲(chǔ)于哈希表中闰挡。
再去遍歷B鏈表锐墙,判斷是否有重復(fù)節(jié)點(diǎn),如果有則返回第一個(gè)查到的節(jié)點(diǎn)长酗。如果B中所有節(jié)點(diǎn)都不在哈希集合中溪北,則兩個(gè)鏈表不相交,返回null夺脾。
2之拨、雙指針,一個(gè)指針走到頭咧叭,然后指向另一個(gè)鏈表頭指針蚀乔,如果有交點(diǎn)就會(huì)相遇。
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(!headA || !headB){
return NULL;
}
struct ListNode *p = headA;
struct ListNode *q = headB;
while(p != q){
p = p != NULL ? headA->next : headB;
q = q != NULL ? headB->next : headA;
}
return p;
}
1菲茬、兩數(shù)之和:給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)整數(shù)目標(biāo)值 target吉挣,請(qǐng)你在該數(shù)組中找出 和為目標(biāo)值 target 的那 兩個(gè) 整數(shù),并返回它們的數(shù)組下標(biāo)婉弹。
1睬魂、暴力兩邊循環(huán)
2、兩遍哈希镀赌,第一
3氯哮、單次哈希,通過哈希查找value商佛,沒有則根據(jù)key喉钢,存value姆打。